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

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


当前回答

this="$(dirname "$(realpath "$BASH_SOURCE")")"

这将解析符号链接(realpath会这样做),处理空格(双引号会这样做),并将找到当前脚本名称,即使是在来源(. ./myscript)或被其他脚本调用时($BASH_SOURCE会这样做)。在所有这些之后,最好将其保存在环境变量中以便重用或方便复制到其他地方(this=)…

其他回答

像这样的东西?

export LC_ALL=en_US.UTF-8
#!/bin/bash
#!/bin/sh

#----------------------------------------------------------------------
start_trash(){
ver="htrash.sh v0.0.4"
$TRASH_DIR  # url to trash $MY_USER
$TRASH_SIZE # Show Trash Folder Size

echo "Would you like to empty Trash  [y/n]?"
read ans
if [ $ans = y -o $ans = Y -o $ans = yes -o $ans = Yes -o $ans = YES ]
then
echo "'yes'"
cd $TRASH_DIR && $EMPTY_TRASH
fi
if [ $ans = n -o $ans = N -o $ans = no -o $ans = No -o $ans = NO ]
then
echo "'no'"
fi
 return $TRUE
} 
#-----------------------------------------------------------------------

start_help(){
echo "HELP COMMANDS-----------------------------"
echo "htest www                 open a homepage "
echo "htest trash               empty trash     "
 return $TRUE
} #end Help
#-----------------------------------------------#

homepage=""

return $TRUE
} #end cpdebtemp

# -Case start
# if no command line arg given
# set val to Unknown
if [ -z $1 ]
then
  val="*** Unknown  ***"
elif [ -n $1 ]
then
# otherwise make first arg as val
  val=$1
fi
# use case statement to make decision for rental
case $val in
   "trash") start_trash ;;
   "help") start_help ;;
   "www") firefox $homepage ;;
   *) echo "Sorry, I can not get a $val   for you!";;
esac
# Case stop
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。

$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 ------------- #

如果不带路径,可以使用${0##*/}