无效的Bash别名

3
在Mac OS X上,我正在将别名添加到我的.bash_profile中。起初我使用了alias命令,但由于它是一个构建命令,所以我发现function更适合。
我尝试了以下内容:
alias ='echo "build with fun."'
alias ='echo "build with tools."'
alias ='echo "build with style."'

奇怪的是,$并不是一个有效的别名,因为bash会报错:

-bash: alias: `': invalid alias name

为什么会这样呢?

你尝试过将 `` 用引号(单引号或双引号)括起来吗? - Some programmer dude
是的,同样的问题... - TTT
2个回答

5

由于某种原因,shell希望引用该名称,并相应地禁止其作为别名。 general.c:legal_alias_name().

尽管locale输出所有值均为'en_US.UTF-8'。

尝试使用不同的表情符号:

~$ alias ='echo oh bother'
~$ 
oh bother
~$ alias ='echo build'
bash: alias: `': invalid alias name
--> 1

为什么 shell 希望引用该名称? 我的第一个猜测是,🤕来自 Unicode 7.0,而 💩来自 Unicode 6.0。我使用 ls 的行为来证明了这一点:

~$ touch  
~$ ls -b  
                \360\237\233\240

在Linux上,我可以将“😊”作为别名使用,但在macOS上却不行。这是因为,尽管我已经使用了Homebrew安装了最新版本的bash,但macOS自带的bash版本较旧。

为了测试这个理论,我还尝试了Unicode 6.0中的“😉”:

$ alias ,='echo choo choo'
bash: alias: `,': invalid alias name
--> 1

所以这不是问题所在!在Linux上,bash很高兴将所有这些字符用作别名。(ls的行为是一个红鱼,因为它会将(7.0)打印为utf-8,但是Mac上的bash将其接受为别名。)但是,别名函数似乎将字符串视为字节而不是字符,这两种失败都以 0xA0 结束,我知道在Latin-1中它是“不间断空格”。不跳进所有C宏声明,我敢打赌那个字符是可疑的。
Mac$ alias $'\u00a0'=foo 
bash: alias: ` ': invalid alias name
--> 1
Linux$ alias $'\u00a0'=foo
Linux$ $'\u00a0'
 : command not found
--> 127

显然,选择一个UTF-8编码中不包含A0字节的字符。但是我不知道为什么我的Linux机器忽略了这个检查。


1
Mac做错了,'0xA0'是UTF-8合法的延续字节。将有效的UTF-8解释为ISO-8859-1是错误和不正确的。那个“检查”没有真正的意义。 - user8017719

1

你需要使用反斜杠\来忽略特殊含义。

alias \='echo "以乐趣构建。"'
alias \='echo "用工具构建。"'
alias \='echo "以风格构建。"

测试:

$  tes*
test  test_script.sh  test.sh  test.xml
$grep '' .bash_profile

别名 \='ls'

ct@MBA45:code$ alias ='echo "用乐趣构建。"' ct@MBA45:code$ alias ='echo "用工具构建。"' -bash: alias: `': 无效的别名名称 - Cees Timmerman
在Sierra 10.12.06上运行良好。GNU bash,版本3.2.57(1)-release(x86_64-apple-darwin16) $ alias \ ='echo“愉快地构建。”' $ 愉快地构建。 - ShpielMeister

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接