bash - 如何为 "two"字写别名

标签 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/

相关文章:

bash - 在 shell 脚本中添加第一个命令问题的答案

macos - 关闭终端后在后台运行进程

bash - Linux 上的文件锁

bash - 如何检测脚本是否正在获取

linux - 如何检查包含变量的字符串是否存在于 bash 的特定文件中?

linux - Webapp更新shell脚本

linux - 在非标准文件的模式匹配之前打印字符串

regex - 尝试将某些文件类型复制到新目录时出错

linux - 无法覆盖到文件

bash - 回显传递给带有可见引号的命令的确切命令行