如何确定脚本本身中的Bash脚本文件的名称?
就像如果我的脚本在文件runme.sh中,那么我如何让它显示“您正在运行runme.sh”消息而不硬编码?
如何确定脚本本身中的Bash脚本文件的名称?
就像如果我的脚本在文件runme.sh中,那么我如何让它显示“您正在运行runme.sh”消息而不硬编码?
当前回答
如果你调用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"
其他回答
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。
在bash中,您可以使用$0获取脚本文件名。通常$1,$2等用于访问CLI参数。类似地,$0是访问触发脚本的名称(脚本文件名)。
#!/bin/bash
echo "You are running $0"
...
...
如果你使用/path/to/script.sh这样的路径调用脚本,那么$0也会给出带有路径的文件名。在这种情况下,需要使用$(basename $0)来获取脚本文件名。
回显“您正在运行$0”
我发现这一行总是有效的,无论文件是源文件还是作为脚本运行。
echo "${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}"
如果你想遵循符号链接,在上面得到的路径上使用readlink,递归或非递归。
单行程序工作的原因可以通过使用BASH_SOURCE环境变量及其关联的FUNCNAME来解释。
BASH_SOURCE An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}. FUNCNAME An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is "main". This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect and return an error status. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset. This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. The caller builtin displays the current call stack using this information.
[来源:Bash手册]
如果你调用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"