
Wednesday July 07, 2004
ksh scripting #1: ME=${0##*/}
True to the tradition of unix, this is as cryptic as it gets, but... elegant [GEEK!]
#!/bin/ksh
ME=${0##*/}
ME here gets the name of the script without the path, effectively doing a basename(1) without the burden of a fork and exec process invocation.
${0} - is command line token 0, i.e. the script filename
## - strips the largest leading string matching the pattern that follows
*/ - this pattern with ## matches everything upto and including the last '/', this is shell wildcard (patmat), not regex
For those who like filename with obvious indication of it's genre, e.g. blah.sh , do this:
#!/bin/ksh
ME=${0##*/}
ME=${ME%.*}
% - strips the smallest trailing string matching the pattern that follows
.* - this pattern with % matches the last '.' (dot is not a wildcard in shell, '?" is) and upto the end of string
I always use $ME in my usage() function,
usage () {
cat <<__UsageEnd__
usage: ${ME} [options] args...
options:
-a ah
-b blah
__UsageEnd__
}
and any error output,
perr () {
echo "${ME}: ${SEVERITY}: ${MSGTXT}"
}
Since my job does more code reading than writing, what's left is the occasional need to automate some test, so shell does it just fine. Instant and disposable (i.e. no worries about reusable values). Nevertheless, there are a few tricks here and there that I like to remember.
(2004-07-07 00:00:01.0)
Permalink
|