如何在我的bashrc中检查是否已设置别名。如何在我的bashrc中检查是否已设置别名
当我一个源文件的bashrc,其中有一个函数名,说乐趣,和我目前的环境有一个别名为乐趣也。
我试过unalias乐趣,但是这会给我一个错误,当我的环境不会有这个别名时就没有找到乐趣。
所以在我的bashrc中,在我的fun函数中,我想检查是否设置了别名,然后unalias。
如何在我的bashrc中检查是否已设置别名。如何在我的bashrc中检查是否已设置别名
当我一个源文件的bashrc,其中有一个函数名,说乐趣,和我目前的环境有一个别名为乐趣也。
我试过unalias乐趣,但是这会给我一个错误,当我的环境不会有这个别名时就没有找到乐趣。
所以在我的bashrc中,在我的fun函数中,我想检查是否设置了别名,然后unalias。
如果你只是想确保别名不存在,只是unalias它和它的错误重定向到/ dev/null的是这样的:
unalias foo 2>/dev/null
如果一个别名设置与您可以检查是这样的:
alias foo 2>/dev/null >/dev/null && echo "foo is set as an alias"
正如手册页指出:
For each name in the argument list for which no value is sup-
plied, the name and value of the alias is printed. Alias
returns true unless a name is given for which no alias has been
defined.
只需使用命令alias
像
alias | grep my_previous_alias
请注意,您可以实际使用unalias
,所以你可以不喜欢
[ `alias | grep my_previous_alias | wc -l` != 0 ] && unalias my_previous_alias
,如果它被设置,将删除该别名。
您可以使用type
查看命令是否存在,或者是否是别名。
如果找不到命令,它将返回错误状态。
例如,我定义以下别名:
$ alias foo="printf"
然后检查以下方案:
$ type foo >/dev/null && echo Command found. || echo Command not found.
Command found.
或专门为别名:
$ alias foo && echo Alias exists || echo Alias does not exist.
,或者检查无论是别名还是常规命令:
$ grep alias <(type foo) && echo It is alias. || echo It is not.
要检查别名是否在您的rc文件中定义,需要手动检查它,例如,由:
[ "$(grep '^alias foo=' ~/.bash* ~/.profile /etc/bash* /etc/profile)" ] && echo Exists. || echo Not there.
好特定的bash-溶液来检查别名使用BASH_ALIASES阵列,例如是:
$ echo ${BASH_ALIASES[ls]}
您可以使用下面的方法使你的.bashrc文件简单:
alias fun=''
unalias fun
fun()
{
# Define the body of fun()
}
我用这个来测试'我的Mac和Linux机器之间la'。在Mac上的.bash_profile中,我有'alias la ='ls -GA'(因为G是彩色的),然后在我的'.bashrc'中有函数checkLa(){if [“$(alias | grep la) “==”ls -GA“];然后回显“mac用户!”;返回0; fi echo“linux user!”; alias la ='ls -A --color = auto'}; checkLa()'。我知道别名也会返回所有的别名,但我只是没有想到它! :d – dylnmc 2014-09-23 21:02:20