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

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


当前回答

为了回答Chris Conway的问题,在Linux上(至少)你会这样做:

echo $(basename $(readlink -nf $0))

Readlink输出符号链接的值。如果不是符号链接,则打印文件名。-n告诉它不打印换行符。-f告诉它完全跟随链接(如果一个符号链接是到另一个链接的链接,它也会解析那个链接)。

其他回答

DIRECTORY=$(cd `dirname $0` && pwd)

我从另一个堆栈溢出问题得到了上面,Bash脚本可以告诉它存储在什么目录中吗?,但我认为它对这个话题也很有用。

me=`basename "$0"`

对于读取symlink1,这通常不是你想要的(你通常不想以这种方式迷惑用户),尝试:

me="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")"

在我看来,这会产生令人困惑的输出。“我跑了foo.sh,但它说我跑了bar.sh!?”一定是虫子!”此外,使用不同名称的符号链接的目的之一是根据其名称提供不同的功能(例如某些平台上的gzip和gunzip)。


1也就是说,为了解析符号链接,当用户执行foo.sh时,它实际上是一个到bar.sh的符号链接,你希望使用解析的名称bar.sh而不是foo.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"

由于一些注释询问没有扩展名的文件名,这里有一个示例如何完成:

FileName=${0##*/}
FileNameWithoutExtension=${FileName%.*}

享受吧!