如何在 bash 别名中使用空格?

six*_*ude 144 unix bash alias

我正在尝试在 bash 中创建别名。我想做的是映射ls -lals -la | more

在我的 .bashrc 文件中,这是我尝试的:

alias 'ls -la'='ls -la | more'

但是它不起作用,因为(我假设)它的别名中有空格。有解决办法吗?

Den*_*son 165

击文档状态“对于几乎所有目的,壳功能优于别名”。这是一个 shell 函数,如果参数由 (only) 组成,它会替换ls并导致输出通过管道传输。more-la

ls() {
    if [[ $@ == "-la" ]]; then
        command ls -la | more
    else
        command ls "$@"
    fi
}
Run Code Online (Sandbox Code Playgroud)

作为单线:

ls() { if [[ $@ == "-la" ]]; then command ls -la | more; else command ls "$@"; fi; }
Run Code Online (Sandbox Code Playgroud)

自动管道输出:

ls -la
Run Code Online (Sandbox Code Playgroud)

  • @merlinpatt:`command` 防止函数被递归调用。 (10认同)
  • 为什么 if 语句中需要使用双括号? (2认同)
  • @sixtyfootersdude:双括号形式更强大,我习惯使用它。见 http://mywiki.wooledge.org/BashFAQ/031 (2认同)

hea*_*vyd 63

别名手册页

每个简单命令的第一个单词,如果没有被引用,则检查它是否有别名。如果是,则该词将替换为别名的文本。别名和替换文本可以包含任何有效的 shell 输入,包括 shell 元字符,但别名可能不包含 `='。

因此,只检查第一个单词的别名匹配,这使得多单词别名变得不可能。您可以编写一个 shell 脚本来检查参数并在它们匹配时调用您的命令,否则只调用正常的ls(参见@Dennis Williamson 的回答

  • +1 用于解释为什么我不允许使用 ls -la 作为别名。 (10认同)
  • 这很有帮助,因为它回答了问题,而不是试图解决它。我来到这里是因为我想创建一个带有空格的别名,而这不会发生。 (9认同)
  • 这不仅回答了我的问题,而且让我对别名机制的实际工作原理有了宝贵的了解。您从手册页中引用的内容非常有帮助。 (2认同)

ld_*_*pvl 19

从丹尼斯的回答中采取的一种稍微改进的方法:

function ls() {
  case $* in
    -la* ) shift 1; command ls -la "$@" | more ;;
    * ) command ls "$@" ;;
  esac
}
Run Code Online (Sandbox Code Playgroud)

或单线:

function ls() { case $* in -la* ) shift 1; command ls -la "$@" | more ;; * ) command ls "$@" ;; esac }
Run Code Online (Sandbox Code Playgroud)

这允许在需要时在命令后附加更多选项/参数,例如 ls -la -h

  • 如果我希望将 `ls -lat` 排除在这种处理之外,这将如何处理?我需要在 `-la*` 条目上方放置一个案例来处理它,是吗? (2认同)