Thursday, February 25, 2010

bash vs. -bash

Spent the last two days running around in circles, trying to figure out why this stupid script wouldn't work.  It's one line, and I was testing it from the command line.  Worked fine in a script:

root@dg scripts]# cat foo
#!/bin/bash
ERR="Error from $(basename $0)";echo $ERR
[root@dg scripts]# foo
Error from foo
Failed miserably by itself:

[root@dg scripts]# ERR="Error from $(basename $0)";echo $ERR
basename: invalid option -- b
Try `basename --help' for more information.
Error from

The good folks at Linuxquestions.org were a big help.  Seems that if the file is executed, it'll behave as you think it should:

[root@tolstoy scripts]# cat foo
#! /bin/bash
  echo $0

[root@tolstoy scripts]# foo
/usr/local/scripts/foo

but if it's ever sourced - as your shell might be, after passing through /etc/profile, ~.bash_profile, etc.:

[root@tolstoy scripts]# . foo
-bash

In fact:

[root@tolstoy scripts]# echo $0
-bash

so my basename $0 became basename -bash, and it failed because it didn't know what the -b option is.

No comments:

Post a Comment