www. On IT Road .com
在 bash 脚本中使用别名
可以使用以下方法使别名命令在 bash 脚本中工作。
可以在 bash 脚本中使用变量来设置任何命令的首选选项,并且可以在脚本的后面部分引用这些变量以满足脚本内部别名的需要。
在脚本的开头添加命令'shopt -s expand_aliases'以扩展别名并使别名命令在bash脚本中工作。
# cat script.sh #!/bin/bash # Script to check the alias output shopt -s expand_aliases alias ls1='ls -lrt' ls1
# chmod +x script.sh # ./script.sh total 0 -rw-r--r-- 1 root root 0 Oct 12 12:14 file1 -rw-r--r-- 1 root root 0 Oct 12 12:14 file2
'set alias ' 用于任何命令,alias 命令在交互式 shell 上可以正常工作,而别名在脚本中不起作用。
- 交互式shell
# alias ls1='ls -lrt' # ls1 total 0 -rw-r--r-- 1 root root 0 Oct 12 12:14 file1 -rw-r--r-- 1 root root 0 Oct 12 12:14 file2
- 脚本内部
# cat script.sh #!/bin/bash # Script to check the alias output alias ls1='ls -lrt' ls1
# chmod +x script.sh # ./script.sh ./script.sh: line 3: ls1: command not found
当 shell 不是交互式时,别名不会被扩展,除非 expand_aliases shell 选项是使用 shopt 设置的。
可以通过向简单的 bash 脚本添加命令“alias”来测试它,脚本执行不会给出别名命令,而在交互式 shell 上,它将提供可用的别名列表,如上例所示。
从 Bash 的手册页:
Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS below).
日期:2020-09-17 00:13:42 来源:oir作者:oir