Reputation: 3083
I have what amounts to a very simple bash script that executes a deployment. Here is my code:
#!/usr/bin/env bash
function print_help
{
echo '
Deploy the application.
Usage:
-r reinstall
-h show help
'
}
reinstall=false
while getopts "rh" opt; do
case ${opt} in
r)
echo "clean"
reinstall=true
;;
h)
echo "help"
print_help
exit 0
;;
esac
done
I am calling the script as follows:
. deploy.sh -h
No matter what I do, neither option (i.e. -r, -h) results in the respective echo
and in the case of -h
the print_help
function isn't called.
What am doing wrong?
Upvotes: 0
Views: 2673
Reputation: 301
If there's a space between the dot and your script name then you're not lauching the script but just sourcing it to your current shell session !
if you want to run your scipt you should do :
# chmod +x ./deploy.sh
# ./deploy.sh -h
if you source it the functtions and variables inside your scipt will be available in your current shell session this could allow you to do things like that :
# . ./deploy.sh
# print_help
Upvotes: 0
Reputation: 141930
getopts
uses a global variable OPTIND
to keep track about which argument it processes currently. Each option it parses, it increments/changes OPTIND
to keep track which argument will be next.
If you call getopt
without changing OPTIND
it will start from where it last ended. If it already parsed first argument, it would want to continue parsing from the second argument, etc. Because there is no second argument the second (or later) time you source your script, there is only -h
, getopt
will just fail, because it thinks it already parsed -h
.
If you want to re-parse arguments in current shell, you need to just reset OPTIND=1
. Or start a fresh new shell, which will reset OPTIND
to 1
by itself.
Upvotes: 1