/bin/sh Can one Easily Strip Path Name from $0?

Michaël Grünewald michael.grunewald at laposte.net
Wed Nov 14 10:13:31 PST 2007

Martin McCormick <martin at dc.cis.okstate.edu> writes:

> 	I am ashamed to admit that I have been writing shell
> scripts for about 15 years but this problem has me stumped. $0
> is the shell variable which contains the script name or at least
> what name is linked to the script. The string in $0 may or may
> not contain a path, depending upon how the script was called. It
> is easy to strip off the path if it is always there
> #! /bin/sh
> PROGNAME=`echo $0 |awk 'BEGIN{FS="/"}{print $NF}'`
> echo $PROGNAME

As said by others, you can use `basename`. Apart from this, you can
fix your old habit by prepending a '/' before '$0', like this:

#! /bin/sh
PROGNAME=`echo /$0 |awk 'BEGIN{FS="/"}{print $NF}'`

Last, you can also use variable expansions mechanisms by saying:


The main difference with `basename` way is that the latter do not call
a subprogram.

(If you are sure there is no space in your name, you can remove the
quotes, but are you sure?)

See `Parameter Expansion' in sh(1).
Best wishes,

More information about the freebsd-questions mailing list