How do I know the script file name in a Bash script? How do I know the script file name in a Bash script? linux linux

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


me=`basename "$0"`

For reading through a symlink1, which is usually not what you want (you usually don't want to confuse the user this way), try:

me="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")"

IMO, that'll produce confusing output. "I ran foo.sh, but it's saying I'm running bar.sh!? Must be a bug!" Besides, one of the purposes of having differently-named symlinks is to provide different functionality based on the name it's called as (think gzip and gunzip on some platforms).


1 That is, to resolve symlinks such that when the user executes foo.sh which is actually a symlink to bar.sh, you wish to use the resolved name bar.sh rather than foo.sh.


# ------------- SCRIPT ------------- ##!/bin/bashechoecho "# arguments called with ---->  ${@}     "echo "# \$1 ---------------------->  $1       "echo "# \$2 ---------------------->  $2       "echo "# path to me --------------->  ${0}     "echo "# parent path -------------->  ${0%/*}  "echo "# my name ------------------>  ${0##*/} "echoexit# ------------- 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 ------------- #


With bash >= 3 the following works:

$ ./s0 is: ./sBASH_SOURCE is: ./s$ . ./s0 is: bashBASH_SOURCE is: ./s$ cat s#!/bin/bashprintf '$0 is: %s\n$BASH_SOURCE is: %s\n' "$0" "$BASH_SOURCE"