Getting the program name in scripts (tummy.com, ltd. Journal Entry)
tummy.com: we do linux

Thursday August 26, 2010 at 16:51
Subject: Getting the program name in scripts
Keywords: bash, NCLUG, Technical
Posted by: Sean Reifschneider

In the (distant) past I've used "`basename $0`" to get the name of the currently running script.

However, several years ago I learned about "${0##*/}", and have switched over to using that. The benefit is that you don't have to fork a new process, and it's also very concise, but admittedly more archaic than "basename".

The way I remember it is that you can do "${var%glob}" "${var%%glob}" "${var#glob}" "${var##glob}", where they strip either at the beginning or the end of the string. The single version is non-greedy match (matches the shortest match) and the double matches greedily. I remember which one is front versus end by thinking that "#" is like a comment, and comments often come at the beginning of the line. :-) So "${0##*/}" means "strip everything before the last / of $0".
(Post Reply)

Comment
Davide Del Vento
Subject: Re: Getting the program name in scripts
Interesting.

The rest of the story (which is often more useful in what I usually do with scripts) if getting the fully qualified path of where the script is. I get it with:

SCRIPTDIR=$( cd -P -- "$(dirname -- "$(command -v -- "$0")")" && pwd -P )