Reputation: 462
I'm currently having problems with my script. Basically, what I want to happen is when I execute ./apache_new_vhost.sh -a -d google.com
, it will create a file and directories and if I use the -r option, it should delete.
The script was able to use the functions like add_vhost. It could create a configuration and folder however the filename is empty because it could not read the value I passed to $domain
.
while getopts ":a:r:d:h" opt; do
case $opt in
a) action=add_vhost
;;
r) action=remove_vhost
;;
d) domain=$OPTARG
;;
h) usage
exit 1
;;
\?) echo "Invalid option: -$OPTARG"
usage
exit 1
;;
:) echo "Error: option -$OPTARG requires an argument."
usage
exit 1
;;
esac
done
#if [ -z $domain ]; then
# usage
# exit 1
if [ $action == "add_vhost" ]; then
echo $action $domain
elif [ $action == "remove_vhost" ]; then
echo $action $domain
fi
Upvotes: 0
Views: 2475
Reputation: 25875
As per your script you expect argument after option -a
. So when you execute your script by
./apache_new_vhost.sh -a -d google.com
then -d
will consider as argument given to -a
option. So your second argument discarded.To solve it just give any argument after -a
(ex: ./apache_new_vhost.sh -a 1 -d google.com )option or make changes in your getopt
while getopts ":ar:d:h" opt; do
Upvotes: 0
Reputation: 206699
The options are processed in the order you specify them on the command line. So in your example, case a)
is processed first, and calls your add_vhost
function right then.
But the d)
case hasn't been processed yet, so you haven't set domain
.
You need to change your logic a bit. Rather than calling your functions directly from the case statement, save what action was selected. i.e.:
a) action="add_vhost"
;;
Then after the case, check that you do have an action
selected, and call that function.
Upvotes: 1