我有一个别名alias ll='ls -lF'
;
我创建了一个 bash 脚本temp.sh
:
#!/bin/bash
# Allow aliases to work in bash NON-interactive mode!
shopt -s expand_aliases
# .. and load them
source ~/.bash_aliases
$1
但是当我运行它时它给了我:
$ ./temp.sh ll
./temp.sh: line 10: ll: command not found
当我更改脚本并直接输入别名时:
#!/bin/bash
# Allow aliases to work in bash NON-interactive mode!
shopt -s expand_aliases
# .. and load them
source ~/.bash_aliases
ll
...它正在工作:
$ ./temp.sh
total 12
-rwxrwxr-x 1 sobi3ch sobi3ch 423 Apr 19 14:21 script.sh*
-rwxrwxr-x 1 sobi3ch sobi3ch 196 Apr 26 12:28 temp.sh*
-rwxrwxr-x 1 sobi3ch sobi3ch 173 Apr 26 12:02 script2.sh
alias
...此外,当我在脚本中运行命令而不是ll
(或$1
)时,我可以看到所有别名之间的别名ll
。
当我将别名作为参数传递时,为什么它不起作用?
答案1
文档中没有明确指出这一点(至少我没有注意到),但问题是别名扩展优先于变量扩展;这意味着$1
检查标记以查看它是否对应于别名,将其作为潜在别名丢弃,然后才将其扩展为参数。由于没有名为的命令ll
,Bash 会出错。
您可以使用eval
使参数扩展两次,第一次作为参数,第二次作为别名:
#!/bin/bash
# Allow aliases to work in bash NON-interactive mode!
shopt -s expand_aliases
# .. and load them
source ~/.bash_aliases
eval "$1"
~$ cat temp.sh
#!/bin/bash
# Allow aliases to work in bash NON-interactive mode!
shopt -s expand_aliases
# .. and load them
source .bash_aliases
eval "$1"
~$ cat .bash_aliases
alias ll='ls -l'
~$ ./temp.sh ll
drwxrwxr-x 3 user user 4096 apr 24 15:18 articles
drwxrwxr-x 2 user user 4096 apr 24 00:20 bin
drwxr-xr-x 2 user user 4096 apr 21 20:22 Documenti
-rw-r--r-- 1 user user 8980 apr 21 20:18 examples.desktop
drwxr-xr-x 2 user user 4096 apr 21 21:59 Immagini
drwxr-xr-x 2 user user 4096 apr 21 20:22 Modelli
drwxrwxr-x 6 user user 4096 apr 23 20:45 MT7630E
drwxr-xr-x 2 user user 4096 apr 21 20:22 Musica
drwxr-xr-x 2 user user 4096 apr 21 20:22 Pubblici
drwxr-xr-x 2 user user 4096 apr 24 23:02 Scaricati
drwxr-xr-x 2 user user 4096 apr 24 13:44 Scrivania
-rwxrwxr-x 1 user user 149 apr 26 13:22 temp.sh
drwxrwxr-x 2 user user 4096 apr 26 13:22 tmp
drwxrwxr-x 24 user user 4096 apr 23 13:45 util-linux-2.28
drwxr-xr-x 2 user user 4096 apr 21 20:22 Video