From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 20309 invoked by alias); 29 Jul 2011 00:45:23 -0000 Mailing-List: contact zsh-users-help@zsh.org; run by ezmlm Precedence: bulk X-No-Archive: yes List-Id: Zsh Users List List-Post: List-Help: X-Seq: 16151 Received: (qmail 1238 invoked from network); 29 Jul 2011 00:45:21 -0000 X-Spam-Checker-Version: SpamAssassin 3.3.1 (2010-03-16) on f.primenet.com.au X-Spam-Level: X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00 autolearn=ham version=3.3.1 Received-SPF: none (ns1.primenet.com.au: domain at benizi.com does not designate permitted sender hosts) Date: Thu, 28 Jul 2011 20:44:52 -0400 (EDT) From: "Benjamin R. Haskell" To: TJ Luoma cc: Zsh Users Subject: Re: how to refer to basename of $0 In-Reply-To: Message-ID: References: User-Agent: Alpine 2.01 (LNX 1266 2009-07-14) MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII; format=flowed On Thu, 28 Jul 2011, TJ Luoma wrote: > I am trying to move a bunch of my scripts to zsh instead of bash > because I'm starting to run into little differences in the way things > are handled which are annoying, and I figured it made more sense to > just learn one way rather than two. > > I have a ".source" file that I use to setup some functions and > variables for use in my scripts, and one of the things it does it > this: > > NAME=`basename $0` > > which, in bash, gives me the basename of the script. For example, if > the script "foo.sh" read .source like this: > > . $HOME/.source > > and then I did > > echo "$NAME" > > it would give me > > foo.sh > > but in zsh I get > > zsh Sounds like you're not actually 'source'-ing the script. $0 should give you the script name in that case. $0 will vary if it's in the top-level scope or inside a function, though. For finer-grained control, you can use the '(%)' parameter expansion flag on the string "%x". (also see %N, but that has the same caveats as $0, AFAIK.) Try the script below, running in these several ways: . ./basename-0.zsh ./basename-0.zsh eval "$( basename-0.zsh <<'SCRIPT' #!/bin/zsh echo 0 outside: $0:t afunction () { echo 0 in afunction: $0:t } afunction () { echo 0 in anon: $0:t } echo 0 in a subshell: "$(/bin/echo $0:t)" echo %x outside: ${${(%):-%x}:t} anotherfunc () { echo %x in anotherfunc: ${${(%):-%x}:t} } anotherfunc () { echo %x in anon: ${${(%):-%x}:t} } echo %x in a subshell: "$(/bin/echo ${${(%):-%x}:t})" SCRIPT $ chmod +x basename-0.zsh