3 ms·
I recommend making 'usage' return 0, rather than 1; since asking for help is valid. (Since you use it both for -h and for unknown options, perhaps make it not
by moonchild 6y ago
I recommend making 'usage' return 0, rather than 1; since asking for help is valid.
(Since you use it both for -h and for unknown options, perhaps make it not exit at all, and make the caller exit with an appropriate code?)
Additionally, you should output the actual executable name (as passed in on $0) rather than hardcoding something. So maybe at the top say 'executable=$0; shift'; replace parseflags.sh with $executable; and replace $1 with $0 in your option parse loop.
- bxparks 6y agoI think technically you are correct about --help being valid. But in practice, I use --help only in an interactive context where the exit code does not matter so I've never been bitten by the subtle difference. I tried using $0 years ago, but I didn't like seeing the full path name (or the "./parseflags.sh" string), or maybe it was because I often use shell alias, so the $0 becomes the alias name, or something like that. So now, I just replace the string "parseflags.sh" with the name of the script for each script. I think I tried using $(basename $0) at one point, but didn't like that either, though I don't remember why. I hope that the template is simple enough that people can customize it as they wish. Edit: Fix typo
- stormbrew 6y agojust fyi, `shift` doesn't affect $0, it slides the window of $1..$N back, so you don't want to shift after grabbing $0 and you don't want to change the option loop if you do this. And you can just use $0 everywhere so there's technically no reason to pull it out into a $executable variable, but tbh that gets a bit confusing in functions.