1 basename and $0
I encountered a small issue with someone’s code, basically it’s about
basename "$0"
In Bash, if run it in interactive shell or shell prompt, you will get the following error:
$ basename "$0" basename: invalid option -- 'b' Try 'basename --help' for more information.
Because $0 is -bash, -b makes basename thinks the user specifies an invalid option. The correct way is to terminate option list by the convention using --, that is:
$ basename -- "$0" -bash
I’ve known Bash have unusual $0 when in shell prompt, but never really thought about it until this thing came up. So I decided to check on various shells, just to see if any other gives unusual $0.
2 Table of $0 in various shells
Shell | Version | Command | $0 or equiv. |
---|---|---|---|
bash | The standard GNU Bourne again shell | ||
4.2.45 | bash | -bash | |
sh | sh | ||
ccsh | UNIX Shell for people already familiar with the C language | ||
0.0.4 | ccsh | /tmp/random text | |
int main(int argc, char *argv[]) { printf("%s\n", argv[0]); } |
|||
dash | DASH is a direct descendant of the NetBSD version of ash (the Almquist SHell) and POSIX compliant | ||
0.5.7.3 | dash | dash | |
fish | fish is the Friendly Interactive SHell | ||
2.0.0 | fish | see below | |
$0 is empty string and list in fish is 1-based index, so there is no such $argv[0] | |||
ksh | The Original Korn Shell, 1993 revision (ksh93) | ||
93u+ | ksh | ksh | |
heirloom-sh | Heirloom Bourne Shell, derived from OpenSolaris code SVR4/SVID3 | ||
050706 | jsh | jsh | |
posh | Reimplementation of Bourne shell based on pdksh | ||
0.12 | posh | posh | |
rc | A reimplementation of the Plan 9 shell | ||
1.7.2 | rcsh | rcsh | |
sash | A small (static) UNIX Shell | ||
3.7 | sash | sh | |
squirrelsh | An advanced, cross-platform object oriented scripting shell based on the squirrel scripting language | ||
1.2.7 | squirrelsh | squirrelsh | |
printl(__argv[0]) |
|||
tcsh | Enhanced version of the Berkeley C shell (csh) | ||
6.18.01 | csh | csh | |
tcsh | tcsh | ||
zsh | UNIX Shell similar to the Korn shell | ||
5.0.2 | zsh | zsh |
3 Notes on the table
- The descriptions are from Gentoo Portage.
- Some shells may provides additional shells, for example, Bash also have sh mode.
- ccsh doesn’t really have an interactive shell mode.
- fish doesn’t seem to have $0-equivalent.
4 Conclusion
- Only Bash gives unusual $0 in interactive shell.
- Using -- is a good practice.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.