Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: how to refer to basename of $0
- X-seq: zsh-users 16151
- From: "Benjamin R. Haskell" <zsh@xxxxxxxxxx>
- To: TJ Luoma <luomat@xxxxxxxxx>
- Subject: Re: how to refer to basename of $0
- Date: Thu, 28 Jul 2011 20:44:52 -0400 (EDT)
- Cc: Zsh Users <zsh-users@xxxxxxx>
- In-reply-to: <CADjGqHuKhx9A3HCUBjU4JgRsbj52s7DQ6HGewT=Y9uRMDGD-fg@mail.gmail.com>
- List-help: <mailto:zsh-users-help@zsh.org>
- List-id: Zsh Users List <zsh-users.zsh.org>
- List-post: <mailto:zsh-users@zsh.org>
- Mailing-list: contact zsh-users-help@xxxxxxx; run by ezmlm
- References: <CADjGqHuKhx9A3HCUBjU4JgRsbj52s7DQ6HGewT=Y9uRMDGD-fg@mail.gmail.com>
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)"
--
Best,
Ben
$ cat > 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
Messages sorted by:
Reverse Date,
Date,
Thread,
Author