How do I know the script file name in a Bash scrip

2019-01-03 19:26发布

How can I determine the name of the Bash script file inside the script itself?

Like if my script is in file runme.sh, then how would I make it to display "You are running runme.sh" message without hardcoding that?

22条回答
戒情不戒烟
2楼-- · 2019-01-03 19:53

Since some comments asked about the filename without extension, here's an example how to accomplish that:

FileName=${0##*/}
FileNameWithoutExtension=${FileName%.*}

Enjoy!

查看更多
forever°为你锁心
3楼-- · 2019-01-03 19:53
this="$(dirname "$(realpath "$BASH_SOURCE")")"

This resolves symbolic links (realpath does that), handles spaces (double quotes do this), and will find the current script name even when sourced (. ./myscript) or called by other scripts ($BASH_SOURCE handles that). After all that, it is good to save this in a environment variable for re-use or for easy copy elsewhere (this=)...

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-03 19:56

Here is what I came up with, inspired by Dimitre Radoulov's answer (which I upvoted, by the way).

script="$BASH_SOURCE"
[ -z "$BASH_SOURCE" ] && script="$0"

echo "Called $script with $# argument(s)"

regardless of the way you call your script

. path/to/script.sh

or

./path/to/script.sh
查看更多
smile是对你的礼貌
5楼-- · 2019-01-03 19:58

if your invoke shell script like

/home/mike/runme.sh

$0 is full name

 /home/mike/runme.sh

basename $0 will get the base file name

 runme.sh

and you need to put this basic name into a variable like

filename=$(basename $0)

and add your additional text

echo "You are running $filename"

so your scripts like

/home/mike/runme.sh
#!/bin/bash 
filename=$(basename $0)
echo "You are running $filename"
查看更多
登录 后发表回答