如果已经设置了别名,我怎样才能检查我的bashrc

时间:2012-03-20 08:31:23

标签: aliasing bash

如果已设置别名,我如何检查我的bashrc。

当我发送一个bashrc文件时,它有一个函数名称,说 fun ,而我当前的环境也有一个别名 fun

我尝试了unalias乐趣,但这会给我一个错误,当我的环境不具备该别名时,这个错误很有用。

所以在我的bashrc中,在我的趣味函数中,我想检查是否设置了别名,然后是unalias。

8 个答案:

答案 0 :(得分:29)

如果您只是想确保别名不存在,只需将其取消并将其错误重定向到/ 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.

答案 1 :(得分:9)

只需使用alias命令

alias | grep my_previous_alias

请注意,您可以实际使用unalias,因此您可以执行类似

的操作
[ `alias | grep my_previous_alias | wc -l` != 0 ] && unalias my_previous_alias

如果已设置别名,则会删除别名。

答案 2 :(得分:3)

您可以使用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.

答案 3 :(得分:1)

检查别名的特定于bash的解决方案是使用BASH_ALIASES数组,例如:

$ echo ${BASH_ALIASES[ls]}

答案 4 :(得分:1)

# Test if alias of name exists, and then remove it:
[ "$(type -t name)" = "alias" ] && unalias name

# Test if function of name exists, and then remove it:
[ "$(type -t name)" = "function" ] && unset -f name

答案 5 :(得分:0)

您可以使用以下命令使您的bashrc文件更简单:

  1. 确保存在别名。
  2. Unalias it。
  3. 定义功能
  4. alias fun=''
    unalias fun
    fun ()
    {
       # Define the body of fun()
    }
    

答案 6 :(得分:0)

来自here

if alias <your_alias_name> 2>/dev/null; then 
  do_something
else 
  do_another_thing; 
fi

答案 7 :(得分:0)

根据noonex's答案编写此功能:

unalias_if() {
    local alias_name
    for alias_name; do
        [[ ${BASH_ALIASES[$alias_name]} ]] && unalias "$alias_name"
    done
}

它可以安全地作为

调用
unalias_if alias1 alias2 ...
相关问题