From owner-freebsd-questions@FreeBSD.ORG Wed Nov 14 15:08:58 2007 Return-Path: Delivered-To: freebsd-questions@freebsd.org Received: from mx1.freebsd.org (mx1.freebsd.org [IPv6:2001:4f8:fff6::34]) by hub.freebsd.org (Postfix) with ESMTP id 9BFEA16A419 for ; Wed, 14 Nov 2007 15:08:58 +0000 (UTC) (envelope-from martin@dc.cis.okstate.edu) Received: from m.it.okstate.edu (m.it.okstate.edu [139.78.2.129]) by mx1.freebsd.org (Postfix) with ESMTP id 5676213C469 for ; Wed, 14 Nov 2007 15:08:58 +0000 (UTC) (envelope-from martin@dc.cis.okstate.edu) Received: from dc.cis.okstate.edu (localhost.it.okstate.edu [127.0.0.1]) by m.it.okstate.edu (8.13.8/8.13.8) with ESMTP id lAEF8veZ083725 for ; Wed, 14 Nov 2007 09:08:57 -0600 (CST) (envelope-from martin@dc.cis.okstate.edu) Message-Id: <200711141508.lAEF8veZ083725@m.it.okstate.edu> To: freebsd-questions@freebsd.org Date: Wed, 14 Nov 2007 09:08:57 -0600 From: Martin McCormick Subject: /bin/sh Can one Easily Strip Path Name from $0? X-BeenThere: freebsd-questions@freebsd.org X-Mailman-Version: 2.1.5 Precedence: list List-Id: User questions List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Wed, 14 Nov 2007 15:08:58 -0000 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 That beautifully isolates the script name but if you happen to call the script without prepending a path name such as when the script is in the execution path, you get an error because there are no slashes in the string so awk gets confused. Is there a better way to always end up with only the script name and nothing else no matter whether the path was prepended or not? Thank you. Martin McCormick