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

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


当前回答

在所有情况下获取脚本或源脚本的“真实路径”:

fullname=$(readlink $0)  # Take care of  symbolic links
dirname=${fullname%/*}       # Get (most of the time) the dirname
realpath=$(dirname $BASH_SOURCE) # TO handle sourced scripts
[ "$realpath" = '.' ] && realpath=${dirname:-.}

下面是要生成的bash脚本(在新创建的“workdir”子目录中,在当前目录的“mytest”中),该bash脚本将派生另一个脚本,该脚本将调用bash定义的函数....测试了许多方法来启动它们:

#!/bin/bash
##############################################################

ret=0

fullname=$(readlink $0)  # Take care of  symbolic links
dirname=${fullname%/*}       # Get (most of the time) the dirname
realpath=$(dirname $BASH_SOURCE) # TO handle sourced scripts
[ "$realpath" = '.' ] && realpath=${dirname:-.}

fullname_withoutextension=${fullname%.*}

mkdir -p workdir
cat <<'EOD' > workdir/_script_.sh
#!/bin/bash
##############################################################

ret=0

fullname=$(readlink $0)  # Take care of  symbolic links
dirname=${fullname%/*}       # Get (most of the time) the dirname
realpath=$(dirname $BASH_SOURCE) # TO handle sourced scripts
[ "$realpath" = '.' ] && realpath=${dirname:-.}

fullname_withoutextension=${fullname%.*}

echo
echo "# ------------- RESULTS ------------- #"
echo "# path to me (\$0)----------->  ${0}     "
echo "# arguments called with ---->  ${@}     "
echo "# \$1 ----------------------->  $1       "
echo "# \$2 ----------------------->  $2       "
echo "# path to me (\$fullname)---->  ${fullname} "
echo "# parent path(\${0%/*})------>  ${0%/*}  "
echo "# parent path(\$dirname)----->  ${dirname} "
echo "# my name ----\${0##*/}------>  ${0##*/} "
echo "# my source -\${BASH_SOURCE}->  ${BASH_SOURCE} "
echo "# parent path(from BASH_SOURCE) -> $(dirname $BASH_SOURCE)"
echo "# my function name -\${FUNCNAME[0]}------>  ${FUNCNAME[0]}"
echo "# my source or script real path (realpath)------------------>  $realpath"
echo
[ "$realpath" = "workdir" ] || ret=1
[ $ret = 0 ] || echo "*******************************************************"
[ $ret = 0 ] || echo "***********   ERROR  **********************************"
[ $ret = 0 ] || echo "*******************************************************"

show_params () {
        echo
        echo "# --- RESULTS FROM show_params() ---- #"
        echo "# path to me (\$0)----------->  ${0}     "
        echo "# arguments called with ---->  ${@}     "
        echo "# \$1 ----------------------->  $1       "
        echo "# \$2 ----------------------->  $2       "
        echo "# path to me (\$fullname)---->  ${fullname} "
        echo "# parent path(\${0%/*})------>  ${0%/*}  "
        echo "# parent path(\$dirname)----->  ${dirname} "
        echo "# my name ----\${0##*/}------>  ${0##*/} "
        echo "# my source -\${BASH_SOURCE}->  ${BASH_SOURCE} "
        echo "# parent path(from BASH_SOURCE) -> $(dirname $BASH_SOURCE)"
        echo "# my function name -\${FUNCNAME[0]}------>  ${FUNCNAME[0]}"
        echo "# my source or script real path (realpath)------------------>  $realpath"
        echo
        [ "$realpath" = "workdir" ] || ret=1
        [ $ret = 0 ] || echo "*******************************************************"
        [ $ret = 0 ] || echo "***********   ERROR  **********************************"
        [ $ret = 0 ] || echo "*******************************************************"

}
show_params "$@"

EOD

cat workdir/_script_.sh > workdir/_side_by_side_script_sourced.inc

cat <<'EOD' >> workdir/_script_.sh

echo "# . $realpath/_side_by_side_script_sourced.inc 'hello there' 'william'"
. $realpath/_side_by_side_script_sourced.inc 'hello there' 'william'

[ $ret = 0 ] || echo "*******************************************************"
[ $ret = 0 ] || echo "***********   ERROR  **********************************"
[ $ret = 0 ] || echo "*******************************************************"
EOD

chmod +x  workdir/_script_.sh
[ -L _mytest_ ] && rm _mytest_
ln -s workdir/_script_.sh _mytest_

# ------------- CALLED ------------- #

called_by () {
        echo '=========================================================================='
        echo " Called by : " "$@"
        echo '=========================================================================='
        eval "$@"
}

called_by bash _mytest_
called_by ./_mytest_

called_by bash workdir/_script_.sh
called_by workdir/_script_.sh
called_by . workdir/_script_.sh


# ------------- RESULTS ------------- #

echo
echo
[ $ret = 0 ] || echo "*******************************************************"
[ $ret = 0 ] || echo "***********   ERROR  **********************************"
[ $ret = 0 ] || echo "*******************************************************"
echo
[ $ret = 0 ] && echo ".... location of scripts (\$realpath) should always be equal to $realpath, for all test cases at date".
echo

# ------------- END ------------- #

其他回答

您可以使用$0来确定您的脚本名称(带完整路径)-要获得只有您可以使用该变量的脚本名称

basename $0
echo "$(basename "`test -L ${BASH_SOURCE[0]} \
                   && readlink ${BASH_SOURCE[0]} \
                   || echo ${BASH_SOURCE[0]}`")"

这对./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"

演职员:我综合了多个答案才得到这个答案。

像这样的东西?

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

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