别名的标准用法是为扩展命令编写快捷方式,例如: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[@]}"
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您的真正目标是为子命令添加别名(并且您将来可能希望处理更多子命令),请考虑case如下结构:
ls() {
local subcommand
if (( "$#" == 0 )); then command ls; return; fi
subcommand=$1; shift
case $subcommand in
--color) command ls "$@" ;;
*) command ls "$subcommand" "$@" ;;
esac
}
Run Code Online (Sandbox Code Playgroud)
一些测试,以区分此答案和先前存在的答案之间的正确性:
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"
Run Code Online (Sandbox Code Playgroud)