简体   繁体   English

bash函数与别名冲突

[英]bash function conflict with alias

How could I detect aliases before define same name function in bash script file(this file will be sourced in another script)? 如何在bash脚本文件中定义相同名称函数之前检测别名(此文件将在另一个脚本中获取)?

Something like meta-programming in bash (define another name function if this name is already taken by aliases?) 像bash中的元编程一样(如果这个名称已被别名占用,则定义另一个名称函数?)

$ source t.sh
$ alert 'test'
test
$ type alert
alert is a function
alert () 
{ 
    echo -n "$@"
}

$ alias alert='notify-send --urgency=low -i error'
$ source t.sh
bash: t.sh: line 1: syntax error near unexpected token `('
bash: t.sh: line 1: `alert() { echo "$@"; }'
$ type alert
alert is aliased to `notify-send --urgency=low -i error'

$ cat t.sh
alert() { echo "$@"; }

You don't need to. 你不需要。 Aliases by default are not expanded in non-interactive shells. 默认情况下,别名不会在非交互式shell中展开。

if alias alert 2> /dev/null; then
    echo "'alert' already an alias"
else
    source t.sh
fi

The alias command exists with non-zero status if its single argument is not an alias. 如果alias命令的单个参数不是别名,则该命令以非零状态存在。

Well, which <name> returns 0 if name is an alias. 好吧,如果name是别名,那么which <name>返回0。

So to check if custom_name is already used you can do: 因此,要检查是否已使用custom_name您可以执行以下操作:

if [ $(which custom_name >/dev/null; echo $?) -eq 0 ]
then
    echo "Already aliased"
    return 1
else
    echo "Free to use"
    return 0
fi

Note: This will not check if there is a bash function called custom_name in the current shell. 注意:这不会检查当前shell中是否存在名为custom_name的bash函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM