如何仅打印出脚本名称?


9
[username@notebook ~]$ cat foo.sh 
#!/bin/bash

echo "$0"
[username@notebook ~]$ ./foo.sh
./foo.sh
[username@notebook ~]$ 

问题:如何输出“ foo.sh”?无论如何执行。

Answers:


22

用途basename

#!/bin/bash

basename -- "$0"

如果要将其分配给变量,则可以执行以下操作:

my_name=$(basename -- "$0")

6
如果脚本名以破折号开始这会失败-,你需要basename -- "$0"。使用shell参数扩展可以避免这种情况,并且不要强迫您启动外部命令。
cuonglm

3
@cuonglm,脚本名称不太可能以破折号开头,但这是有效的点。
cjm

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.