如何“堆叠”shell 别名?

如何“堆叠”shell 别名?

在我的.profile(来自shmy 的模拟模式.zshrc)中,我有以下代码片段:

if [ -f /usr/bin/pacmatic ]; then
    alias pacman=pacmatic
fi

# Colorized Pacman output
alias pacman="pacman --color auto"

但是,第二个别名始终会覆盖第一个别名:

% type pacman
pacman is an alias for pacman --color auto

我怎样才能使第二个别名分配“继承”第一个分配,这样如果/usr/bin/pacmatic存在,别名就变成pacmatic --color auto

我并不反对使用函数而不是别名,但如果不是每次调用时都执行逻辑pacman(我想pacmatic在 shell 启动时检查一次,而不是每次pacman运行时检查一次),我更喜欢它。我还更喜欢sh-portable 脚本,但如果不可能,您可以使用完整zsh语法。

(是的,我知道这可以通过附加别名来轻松解决--color autopacmatic但我想以正确的方式完成它™。)

我尝试过谷歌搜索并浏览手册页,但无济于事。

答案1

仅当从交互式源读取行时才执行别名替换。因此第二个别名不受第一个别名的影响,因此是字面替换。

也许类似的东西:

PACMAN=pacman
if [ -f /usr/bin/pacmatic ]; then
    PACMAN=pacmatic
fi

# Colorized Pacman output
alias pacman="${PACMAN} --color auto"

这会将 'pacman' 设置为正确的值,PACMAN 环境变量不会导出,因此当脚本完成时它将消失,并且使用“双引号”将确保变量替换发生在别名的声明中,不适用于每次调用。

我使用类似的方法:

PACMAN=pacman
which pacmatic &>/dev/null && PACMAN=pacmatic
alias pacman="${PACMAN} --color auto"

基本上,设置环境变量 PACMAN,测试路径中的 pacmatic,如果找到,设置 PACMAN,然后定义别名。

嗯,你可以再优化一下...

which pacmatic &>/dev/null && PACMAN=pacmatic
alias pacman="${PACMAN:-pacman} --color auto"

哒哒!如果 PACMAN 未设置或为空,则设置为“pacman”,否则设置为 PACMAN 的值,通过“which”行设置为 pacmatic。

答案2

shell 的alias行为与 非常相似#define,即重新定义 shell 别名将覆盖前一个别名。

我不确定正确的方式TM是什么,但一种方法是使用接受参数的 shell 函数并使用它来创建别名。您的代码片段可以重写为:

if [ -f /usr/bin/pacmatic ]; then
    pacman() { pacmatic "$@"; }
fi

# Colorized Pacman output
alias pacman="pacman --color auto"

 


此外,即使您使用不同的别名并尝试使用一个别名来定义另一个别名,它也不会起作用,因为默认情况下别名不会在非交互模式下扩展。您需要通过设置来启用它expand_aliases

shopt -s expand_aliases

引用手册:

   Aliases are not expanded when the shell is not interactive, unless  the
   expand_aliases  shell option is set using shopt (see the description of
   shopt under SHELL BUILTIN COMMANDS below).

答案3

在 zsh 中,您可以使用以下命令轻松附加到别名aliases关联数组:

alias pacman="${aliases[pacman]-pacman} --color auto"

在其他 shell 中,您需要使用命令的输出alias来查找现有别名。

current_pacman_alias=$(alias pacman 2>/dev/null)
alias pacman="${current_pacman_alias:-pacman} --color auto"

虽然我提供这种可能性,但我会按照其他答案已经建议的那样使用变量。它更清晰,如果您想根据正在使用的pacmatic或之一来不同地配置某些内容,您可以区分变量的值。pacman

pacman==pacmatic 2>/dev/null || pacman=pacman
alias pacman='$pacman --color auto'

答案4

pacman() ( def_args="--color auto" bin=
    [ -x ${bin:=/usr/bin/pacmatic} ] || bin=
    [ -x ${bin:=/usr/bin/pacman} ] || bin= 
    ${bin:?WHERE THE HELL IS PACMAN????} \
        $def_args "$@"
)

别名是鸟类的别名。

相关内容