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

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


当前回答

使用bash >= 3,以下工作:

$ ./s
0 is: ./s
BASH_SOURCE is: ./s
$ . ./s
0 is: bash
BASH_SOURCE is: ./s

$ cat s
#!/bin/bash

printf '$0 is: %s\n$BASH_SOURCE is: %s\n' "$0" "$BASH_SOURCE"

其他回答

使用bash >= 3,以下工作:

$ ./s
0 is: ./s
BASH_SOURCE is: ./s
$ . ./s
0 is: bash
BASH_SOURCE is: ./s

$ cat s
#!/bin/bash

printf '$0 is: %s\n$BASH_SOURCE is: %s\n' "$0" "$BASH_SOURCE"

回复:上面Tanktalus(接受)的答案,一个稍微干净一点的方法是使用:

me=$(readlink --canonicalize --no-newline $0)

如果你的脚本来自另一个bash脚本,你可以使用:

me=$(readlink --canonicalize --no-newline $BASH_SOURCE)

我同意,如果您的目标是向用户提供反馈,那么取消对符号链接的引用可能会令人困惑,但在某些情况下,您确实需要获得脚本或其他文件的规范名称,在我看来,这是最好的方法。

$0将给出您正在运行的脚本的名称。创建一个脚本文件并添加以下代码

#!/bin/bash
echo "Name of the file is $0"

然后像这样从终端运行

./file_name.sh
# ------------- 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"