7

When I reference $0 in a Bash script on my Mac running Mac OS X v10.6.7 (Snow Leopard), I get -bash, not the name of the script.

I ran the script described in this Stack Overflow question:

#!/bin/bash

echo
echo '# arguments called with ($@) -->  '"$@"
echo '# $1 -------------------------->  '"$1"
echo '# $2 -------------------------->  '"$2"
echo '# path to me ($0) ------------->  '"$0"
echo '# parent path (${0%/*}) ------->  '"${0%/*}"
echo '# my name (${0##*/}) ---------->  '"${0##*/}"
echo

The following is produced:

> . show_parms.sh foo

# arguments called with ($@) -->  foo
# $1 -------------------------->  foo
# $2 -------------------------->
# path to me ($0) ------------->  -bash
# parent path (${0%/*}) ------->  -bash
# my name (${0##*/}) ---------->  -bash

Any ideas?

Community
  • 1
  • 1
David Potter
  • 2,272
  • 2
  • 22
  • 35

3 Answers3

9

That makes sense since you’re sourcing the script

. show_parms.sh foo

instead of executing it

./show_parms.sh foo

As explained in this answer to the same question, you can use $BASH_SOURCE to know the name of the file from which commands are being sourced.

Community
  • 1
  • 1
  • 2
    Okay, I'm a dufus. $BASH_SOURCE did the trick. I like that solution as well because it is reliably, giving me what I expected regardless of how the script is invoked. I obviously didn't try everything suggested in that answer. Thanks, Bavarious, for your help. – David Potter May 02 '11 at 02:11
5

$0 returns the name of the process. By using the . operator, you're just reading the script into your existing bash process and evaluating the commands it contains; the name of the process remains "-bash", so that's what you see. You have to actually execute the script as its own process:

chmod +x show_parms.sh
./show_params.sh foo

And then you'll get what you expect. This isn't OS X specific; this is just how bash (or sh) works.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • Thanks Ernest. Since I want to get the script name info regardless of how it was invoked, I'll use $BASH_SOURCE as suggested below, which works both ways. Thanks for your help. – David Potter May 02 '11 at 02:14
2

It is because you are using the . operator. If you just typed

show_parms.sh foo

you would get the result you want.

ditkin
  • 6,774
  • 1
  • 35
  • 37