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条回答
Melony?
2楼-- · 2019-01-03 19:47
# ------------- 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 ------------- #
查看更多
Juvenile、少年°
3楼-- · 2019-01-03 19:48

If the script name has spaces in it, a more robust way is to use "$0" or "$(basename "$0")" - or on MacOS: "$(basename \"$0\")". This prevents the name from getting mangled or interpreted in any way. In general, it is good practice to always double-quote variable names in the shell.

查看更多
对你真心纯属浪费
4楼-- · 2019-01-03 19:48

In bash you can get the script file name using $0. Generally $1, $2 etc are to access CLI arguments. Similarly $0 is to access the name which triggers the script(script file name).

#!/bin/bash
echo "You are running $0"
...
...

If you invoke the script with path like /path/to/script.sh then $0 also will give the filename with path. In that case need to use $(basename $0) to get only script file name.

查看更多
一夜七次
5楼-- · 2019-01-03 19:51

With bash >= 3 the following works:

$ ./s
0 is: ./s
BASH_SOURCE is: ./s
$ . ./s
0 is: bash
BASH_SOURCE is: ./s

$ cat s
#!/bin/bash

printf '$0 is: %s\n$BASH_SOURCE is: %s\n' "$0" "$BASH_SOURCE"
查看更多
再贱就再见
6楼-- · 2019-01-03 19:52

If you want it without the path then you would use ${0##*/}

查看更多
【Aperson】
7楼-- · 2019-01-03 19:52

$0 doesn't answer the question (as I understand it). A demonstration:

$ cat script.sh
#! /bin/sh
echo `basename $0`
$ ./script.sh 
script.sh
$ ln script.sh linktoscript
$ ./linktoscript 
linktoscript

How does one get ./linktoscript to print out script.sh?

[EDIT] Per @ephemient in comments above, though the symbolic link thing may seem contrived, it is possible to fiddle with $0 such that it does not represent a filesystem resource. The OP is a bit ambiguous about what he wanted.

查看更多
登录 后发表回答