用户定义的别名
用户自定义别名由用户定义,通常用于缩写或者自定义常用命令。
例如,在以下代码中使用 alias 命令将 history 命令别名为 h:
$ alias h=history ... 46 cd /usr 47 ls -lrt 48 cd 49 cd /usr/bin 50 ll 51 clear 52 alias 53 alias h=history 54 h
使用 rm 、 cp 和 mv 命令可能会无意中导致数据丢失。
作为预防措施,我们可以使用交互选项为这些命令设置别名。
例如,rm 命令使用 -i 选项作为别名,编码如下:
$ alias rm='rm -i' $ rm file1 rm: remove file1: (yes/no)? no
同样,创建 'cp -i ' 和 'mv -i ' 别名可确保 shell 在覆盖现有文件之前提示我们进行确认。
命令序列
我们可以在一个别名下对多个命令进行分组。
各个命令用分号分隔。
例如:
$ alias info='uname -s; id; date'
Linux uid=1001(user) gid=1001(user) Tue Dec 5 15:11:58 UTC 2017
在以下示例中,使用管道 (|) 创建别名以将 ls -l 命令的输出定向到 more 命令。
调用新别名时,会出现一个目录列表。
$ alias ll='ls -l | more'
$ cd /usr/bin $ ll total 121528 -rwxr-xr-x. 1 root root 41496 Nov 5 2016 [ -rwxr-xr-x. 1 root root 107856 Aug 2 17:46 a2p -rwxr-xr-x. 1 root root 52640 Oct 19 20:40 ab -rwxr-xr-x. 1 root root 29112 Sep 6 16:47 addr2line ... --More-
什么是别名
别名是一种简写的 shell 符号,允许我们自定义和缩写命令。
别名在所有 shell 中都可用。
在命令行上定义别名的常用语法如下:
$ alias name=command_string
如果命令行上的第一个单词是别名,shell 会用别名的文本替换该单词。
shell 维护一个别名列表,当输入命令时它会搜索这些别名。
创建别名时适用以下规则:
- 等号两边不能有空格。
- 如果命令字符串包含任何选项、元字符或者空格,则必须引用它。
- 单个别名中的每个命令都必须用分号分隔。
删除别名
unalias 命令从别名列表中删除别名。
$ unalias alias_name
例如,使用 unalias 命令删除之前创建的 h 别名。
$ unalias h
$ h -bash: h: command not found
预定义别名
shell 包含几个预定义的别名。
我们可以使用 alias 命令显示这些预定义的别名。
例如 :
$ alias alias egrep='egrep --color=auto' alias fgrep='fgrep --color=auto' alias grep='grep --color=auto' alias info='uname -s; id; date' alias l.='ls -d .* --color=auto' alias ll='ls -l | more' alias ls='ls --color=auto' alias vi='vim' alias which='alias | /usr/bin/which --tty-only --read-alias --show-dot --show-tilde'
注意:alias 命令也显示用户定义的别名。
停用别名
我们可以通过在命令行中的别名前面放置一个反斜杠 () 来临时停用别名。
例如,在以下代码中,反斜杠可防止 shell 在别名列表中查找。
这允许 shell 运行原始 rm 命令来删除 file1 文件。
$ rm file1 rm: remove file1 (yes/no)? no
$ \rm file1 $ ls file1 file1: No such file or directory
或者,如果我们使用反斜杠,历史记录的别名如 h 会给出如下错误。
$ \h -bash: h: command not found