$0不够用?
当我们编写shell脚本时,有时候需要获取当前执行脚本的名字,最常用的应该就是$0了,但是根据执行脚本的方式不同,这种方式是有缺陷的,我们执行脚本的可能方式有:123./script.sh. script.shsource script.sh
这几种方式的$0不尽相同,先总结如下:
| 方法 | 描述 |
|---|---|
| $0 | only works when user executes “./script.sh” |
| $BASH_ARGV | only works when user executes “. script.sh” or “source script.sh” |
| ${BASH_SOURCE[0]} | works on both cases. |
| readlink -f | useful when symbolic link is used |