让 sudo 继承 .zshrc 或 .bashrc 中定义的 alias

2018-08-16T16:37:00

在 Linux 下使用 sudo 进行高权限操作时, 如果你在 .zshrc 或者 .bashrc 中设置了一些顺手的 alias 的时候, 你会发现这些 alias 是不能跟随 sudo 命令传递到 shell 中的, 有时候很不方便.

举个例子:

# tink @ Ubuntu in ~ [16:25:42] 
$ alias | grep ll=
ggpull='git pull origin $(git_current_branch)'
ll='ls -lh'

# tink @ Ubuntu in ~ [16:26:39] 
$ ll
total 4K
drwxr-xr-x 9 tink tink 4.0K Jul 20 15:50 script

# tink @ Ubuntu in ~ [16:26:51] 
$ sudo ll
sudo: ll: command not found

解决办法也很简单, 算是一个小 trick.

vi ~/.zshrc
alias sudo='sudo '

注意在 sudo 后面有个空格.


这个解决方法的原理在 bash manual 中有解释:

Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains a list of aliases that may be set and unset with the alias and unalias builtin commands.

The first word of each simple command, if unquoted, is checked to see if it has an alias. If so, that word is replaced by the text of the alias. The characters ‘/’, ‘$’, ‘`’, ‘=’ and any of the shell metacharacters or quoting characters listed above may not appear in an alias name. The replacement text may contain any valid shell input, including shell metacharacters. The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias ls to "ls -F", for instance, and Bash does not try to recursively expand the replacement text. If the last character of the alias value is a space or tab character, then the next command word following the alias is also checked for alias expansion.

当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »