<分区>
别名的标准用法是为扩展命令编写快捷方式,例如:alias ls='ls --color'
。
我想知道是否可以在左侧设置“参数”,以便它以相反的方式工作。使用上面的示例,我很想知道 alias ls --color='ls'
是否可行,也就是说,当有人键入 ls --color
时,运行简单的 ls
。
忘记这是否有用或有意义,我只想知道这是否可能,或者是否有任何解决方法可以实现相同的目标。
标签 bash
<分区>
别名的标准用法是为扩展命令编写快捷方式,例如:alias ls='ls --color'
。
我想知道是否可以在左侧设置“参数”,以便它以相反的方式工作。使用上面的示例,我很想知道 alias ls --color='ls'
是否可行,也就是说,当有人键入 ls --color
时,运行简单的 ls
。
忘记这是否有用或有意义,我只想知道这是否可能,或者是否有任何解决方法可以实现相同的目标。
最佳答案
现有的答案不能正确处理带空格的命令——而且确实不能:将数组压缩成字符串本质上是错误的。
此版本使用参数列表作为数组,从而避免了这种信息丢失:
ls() {
local -a args=( )
for arg; do
[[ $arg = --color ]] || args+=( "$arg" )
done
command ls "${args[@]}"
}
或者,如果您的真正目标是为子命令设置别名(并且您可能希望在将来处理更多子命令),请考虑一个 case
结构,如下所示:
ls() {
local subcommand
if (( "$#" == 0 )); then command ls; return; fi
subcommand=$1; shift
case $subcommand in
--color) command ls "$@" ;;
*) command ls "$subcommand" "$@" ;;
esac
}
一些测试,以区分这个答案和先前存在的答案的正确性:
tempdir=/tmp/ls-alias-test
mkdir -p "$dir"/'hello world' "$dir"/my--color--test
# with the alternate answer, this fails because it tries to run:
# ls /tmp/ls-alias-test/hello world
# (without the quotes preserved)
ls --color "$dir/hello world"
# with the alternate answer, this fails because it tries to run:
# ls /tmp/ls-alias-test/my--test
ls --color "$dir/my--color--test"
关于bash - 如何为 "two"字写别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40654352/