读取脚本名
(1)示例
- $ cat positional0.sh
- #!/bin/bash
- # Handling the $0 command-line parameter
- #
- echo This script name is $0.
- exit
- $
- $ bash positional0.sh
- This script name is positional0.sh.
- $
(2)如果使用另一个命令来运行 shell 脚本,则命令名会和脚本名混在一起,出现在位置变量$0 中:
- $ ./positional0.sh
- This script name is ./positional0.sh.
- $
那么位置变量$0 就会包含整个路径:
- $ $HOME/scripts/positional0.sh
- This script name is /home/christine/scripts/positional0.sh.
- $
(3)如果你编写的脚本中只打算使用脚本名,那就得做点儿额外工作,剥离脚本的运行路径。好在有个方便的小命令可以帮到我们。
basename 命令可以返回不包含路径的脚本名:
- $ cat posbasename.sh
- #!/bin/bash
- # Using basename with the $0 command-line parameter
- #
- name=$(basename $0)
- #
- echo This script name is $name.
- exit
- $
- $ ./posbasename.sh
- This script name is posbasename.sh.
- $
(4)可以使用此技术编写一个脚本,生成能标识运行时间的日志消息:
- $ cat checksystem.sh
- #!/bin/bash
- # Using the $0 command-line parameter in messages
- #
- scriptname=$(basename $0)
- #
- echo The $scriptname ran at $(date) >> $HOME/scripttrack.log
- exit
- $
- $ ./checksystem.sh
- $ cat $HOME/scripttrack.log
- The checksystem.sh ran at Thu 04 Jun 2020 10:01:53 AM EDT
- $