我如何知道Bash脚本中的脚本文件名?
我如何确定脚本本身内的Bash脚本文件的名称?
就像如果我的脚本在文件runme.sh
,那么我将如何让它显示“你正在运行runme.sh”消息而不硬编码?
me=`basename "$0"`
对于通常不是你想要的符号链接(你通常不希望用这种方式混淆用户)来说,请尝试:
me="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")"
国际海事组织,这将产生混乱的输出。 “我跑了foo.sh,但它说我正在运行bar.sh!?必须是一个bug!” 此外,具有不同名称符号链接的目的之一是根据其名称(在某些平台上认为gzip和gunzip)提供不同的功能。
# ------------- 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 ------------- #
随着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: %sn$BASH_SOURCE is: %sn' "$0" "$BASH_SOURCE"
链接地址: http://www.djcxy.com/p/1671.html
上一篇: How do I know the script file name in a Bash script?
下一篇: Reliable way for a bash script to get the full path to itself?