如何确定脚本本身中的Bash脚本文件的名称?
就像如果我的脚本在文件runme.sh中,那么我如何让它显示“您正在运行runme.sh”消息而不硬编码?
如何确定脚本本身中的Bash脚本文件的名称?
就像如果我的脚本在文件runme.sh中,那么我如何让它显示“您正在运行runme.sh”消息而不硬编码?
当前回答
我发现这一行总是有效的,无论文件是源文件还是作为脚本运行。
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手册]
其他回答
回显“您正在运行$0”
简短,清晰,简单,在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.
这对./self.sh, ~/self.sh, source self.sh, source ~/self.sh很有效:
#!/usr/bin/env bash
self=$(readlink -f "${BASH_SOURCE[0]}")
basename=$(basename "$self")
echo "$self"
echo "$basename"
演职员:我综合了多个答案才得到这个答案。
感谢Bill Hernandez提供的信息。我增加了一些我正在采用的偏好。
#!/bin/bash
function Usage(){
echo " Usage: show_parameters [ arg1 ][ arg2 ]"
}
[[ ${#2} -eq 0 ]] && Usage || {
echo
echo "# arguments called with ----> ${@} "
echo "# \$1 -----------------------> $1 "
echo "# \$2 -----------------------> $2 "
echo "# path to me ---------------> ${0} " | sed "s/$USER/\$USER/g"
echo "# parent path --------------> ${0%/*} " | sed "s/$USER/\$USER/g"
echo "# my name ------------------> ${0##*/} "
echo
}
干杯
如果你调用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"