如何确定脚本本身中的Bash脚本文件的名称?

就像如果我的脚本在文件runme.sh中,那么我如何让它显示“您正在运行runme.sh”消息而不硬编码?


当前回答

简短,清晰,简单,在my_script.sh中

#!/bin/bash

running_file_name=$(basename "$0")

echo "You are running '$running_file_name' file."

把:

./my_script.sh
You are running 'my_script.sh' file.

其他回答

# ------------- SCRIPT ------------- #

#!/bin/bash

echo
echo "# arguments called with ---->  ${@}     "
echo "# \$1 ---------------------->  $1       "
echo "# \$2 ---------------------->  $2       "
echo "# path to me --------------->  ${0}     "
echo "# parent path -------------->  ${0%/*}  "
echo "# my name ------------------>  ${0##*/} "
echo
exit

# ------------- CALLED ------------- #

# Notice on the next line, the first argument is called within double, 
# and single quotes, since it contains two words

$  /misc/shell_scripts/check_root/show_parms.sh "'hello there'" "'william'"

# ------------- RESULTS ------------- #

# arguments called with --->  'hello there' 'william'
# $1 ---------------------->  'hello there'
# $2 ---------------------->  'william'
# path to me -------------->  /misc/shell_scripts/check_root/show_parms.sh
# parent path ------------->  /misc/shell_scripts/check_root
# my name ----------------->  show_parms.sh

# ------------- END ------------- #

如果你调用shell脚本喜欢

/home/mike/runme.sh

$0是全名

 /home/mike/runme.sh

Basename $0将获得基本文件名

 runme.sh

你需要把这个基本的名字放到一个变量里,比如

filename=$(basename $0)

并添加额外的文本

echo "You are running $filename"

你的脚本就像

/home/mike/runme.sh
#!/bin/bash 
filename=$(basename $0)
echo "You are running $filename"

如果脚本名中有空格,更可靠的方法是使用"$0"或"$(basename "$0")"-或MacOS: "$(basename \"$0\")"。这可以防止名称以任何方式被破坏或解释。一般来说,在shell中始终使用双引号作为变量名是一种良好的实践。

这些答案对于它们所陈述的情况是正确的,但如果您使用'source'关键字从另一个脚本运行脚本(以便它在同一个shell中运行),仍然存在一个问题。在本例中,您将获得调用脚本的$0。在这种情况下,我认为不可能获得脚本本身的名称。

这是一个边缘情况,不应该太当真。如果你直接从另一个脚本运行脚本(没有'source'),使用$0可以工作。

$BASH_SOURCE在获取脚本时给出正确答案。

然而,这包括路径,所以只获得脚本文件名,使用:

$(basename $BASH_SOURCE)