shell 别名是创建新命令或用自己的代码封装现有命令的一种简单方法。它们与 shell 函数在使用的效果上有些重叠,但后者功能更多,因此通常更受欢迎。
Section 7.1: 绕过别名
有时,您可能希望暂时绕过某个别名,而不是将其禁用。举个具体例子,请看这个别名:
alias ls='ls --color=auto'
比方说,你想在不禁用别名的情况下使用 ls 命令。你有以下几种选择:
- 使用内置命令:
ls命令 - 使用命令的完整路径
/bin/ls - 在命令名称的任意位置添加一个
\,例如\ls,或l\s - 引用命令:
"ls"或'ls'
Section 7.2: 创建别名
alias word='command'
调用 word 将运行命令。为别名提供的任何参数都会被附加到别名的目标中:
alias myAlias='some command --with --options'
myAlias foo bar baz
然后 shell 将执行:
some command --with --options foo bar baz
要在同一个别名中包含多个命令,可以用 && 将它们串起来。例如
alias print_things='echo "foo" && echo "bar" && echo "baz"'
Section 7.3: 删除别名
要删除现有别名,请使用
unalias {alias_name}
例如
# create an alias
$ alias now='date'
# preview the alias
$ now
Thu Jul 21 17:11:25 CEST 2016
# remove the alias
$ unalias now
# test if removed
$ now
-bash: now: command not found
Section 7.4: BASH_ALIASES 是一个 bash 内部关联数组
别名是命令的命名快捷方式,可以在交互式 bash 实例中定义和使用。它们保存在一个名为 BASH_ALIASES 的关联数组中。要在脚本中使用该变量,必须在交互式 shell 中运行该变量
#!/bin/bash -li
# note the -li above! -l makes this behave like a login shell
# -i makes it behave like an interactive shell
#
# shopt -s expand_aliases will not work in most cases
echo There are ${#BASH_ALIASES[*]} aliases defined.
for ali in "${!BASH_ALIASES[@]}"; do
printf "alias: %-10s triggers: %s\n" "$ali" "${BASH_ALIASES[$ali]}"
done
Section 7.5: 扩展别名
假设 bar 是 someCommand -flag1 的别名。
在命令行中键入 bar,然后按 Ctrl + alt + e 键
你就会在 bar 所在的位置得到 someCommand -flag1。
Section 7.6: 列出所有别名
alias -p
将列出所有当前别名。