我最近补充道
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'
Run Code Online (Sandbox Code Playgroud)
到我的bash_aliases文件.玩弄这个,我注意到虽然..允许别名,但是别名.不是.bash别名中允许使用哪些其他标点字符?
使用函数总是更安全:
function .. { cd '..'; }
function ... { cd '../..'; }
function .... { cd '../../..'; }
Run Code Online (Sandbox Code Playgroud)
或者对于保守的偏好:
..() { cd '..'; }
...() { cd '../..'; }
....() { cd '../../..'; }
Run Code Online (Sandbox Code Playgroud)
这样做更安全吗?
别名影响一流的语法(if、case 等),它的命令使用引号指定。这就像不必要地使用 eval 一样。另一方面,使用函数很简单,您确切地知道参数是如何展开的。TL;DR 别名是一个黑客。当您可以简单地定义一个函数时,这就像在 C 中使用 #define 语句一样。这是初学者喜欢创作的东西。
如果有人想为命令定义默认参数,您可以使用 command 使函数调用外部命令以避免递归。这是正确的做法。例如function grep { command grep --color=auto "$@"; }
巴什别名绝对不能包含这些字符:空格,制表\t符,换行符\n,/,$,`,=,|,&,;,(,),<,>,'和"。
bash 的 GNU 手册https://www.gnu.org/software/bash/manual/html_node/Aliases.html说:
字符
/,$,`,=和任何壳或元字符上面列出的引用字符的可能不会出现在一个别名。
“shell 元字符”在https://www.gnu.org/software/bash/manual/html_node/Definitions.html中定义为
不加引号时用于分隔单词的字符。元字符是一个
space,tab,newline,或以下字符中的一个:|,&,;,(,),<,或>。
我找不到“引用字符”列表https://www.gnu.org/software/bash/manual/html_node/Quoting.html。据我所知,它们是单引号'和双"引号。
https://www.gnu.org/software/bash/manual/html_node/Aliases.html 我不会在 linux 中命名别名。是当前目录的特殊名称,.. 是父目录的名称。可能有一些模糊的过程可能会因别名而搞砸..对于 cd