I am unable to parse flags in a function in a bash script.
I have a shell script admin.sh
that I'm sourcing (i.e. source ./admin.sh
). In that script I have function called command_to_do
. The code below shows what I'm trying to accomplish. I want to be able to call command_to_do
from the command line and process all arguments
#!/bin/bash
function command_to_do() {
echo "Args $@"
SYSTEM=false
UNINSTALL=false
PUSH=false
VERSION="debug"
while getopts "sup:" opt; do
printf "\n$opt\n"
case $opt in
s) echo "Setting SYSTEM to true"
SYSTEM=true
;;
p) echo "Setting VERSION to $OPTARG"
PUSH=true
VERSION=$OPTARG
;;
u) echo "Setting UNINSTALL to true"
UNINSTALL=true
;;
esac
done
printf "\nSystem: $SYSTEM\nVersion: $VERSION\n"
if [[ $UNINSTALL = true ]]; then
if [[ $SYSTEM = true ]]; then
echo "system uninstall"
else
echo "non-system uninstall"
fi
fi
}
I'm getting very strange results. The first time I run the command_to_do -s -p release
, it correctly processes the flags and prints the expected results
Args -s -p release
s
Setting SYSTEM to true
p
Setting VERSION to release
System: true
Version: release
Every time after that, it doesn't seem to capture the flags. For instance, running that same command again gives:
Args -s -p release
System: false
Version: debug
If I remove the function declaration (function command_to_do() {}
) and just have the code in the admin.sh
file, everything seems to work fine every time, but I have to call the script with the dot syntax (./admin -s -p release
). The reasoning behind why I don't want to use the dot syntax is not important. I just want to know if it's possible to do what I'm attempting and how.
I've read about passing the arguments to the function with command_to_do $@
, but, as I'm trying to call the function by it's name from the command prompt, this is not applicable and it appears by the echo $@
statement that the arguments are being passed to the function.
I'm new to writing bash scripts so any help would be appreciated.