I've been exploring this issue for longer than it should take me and finding getopts a very confusing tool.
All I want to do is the following. Have a script that I can pass arguments like this $1 $2 $3 and one of them being an optional -e email
So this is what I did, which of course doesn't work at all:
#!/bin/bash
if [[ $# -lt 2 ]] || [[ $# -gt 3 ]]
then
echo
echo "usage is `basename $0` argument1 argument2 {-e email}"
exit 1
fi
while getopts e: flag; do
case $flag in
e)
EMAIL=$OPTARG;
;;
?)
exit;
;;
esac
done
[[ -v $EMAIL ]] && echo "I am sending you $1 and $2!!" | mutt -s "present" $EMAIL && exit 0
echo "I am keeping $1 and $2 to myself"
Of course I could just ignore this getopts business and do without it, I am just trying to learn how to use it properly
-v
point, I somewhat disagree with you. (http://unix.stackexchange.com/questions/212183/how-do-i-check-if-a-variable-exists-in-bash) You are right you can use-n
or! -z
to check a variable exists but-v
should also work in latter versions of bash. And it does work in my tests. – Ulukai Mar 28 '16 at 11:02[[ -v EMAIL ]]
ought to work (but not[[ -v $EMAIL ]]
as you wrote!) however why use a non-portable non-standard bashism when a standard construct like[ -n "$EMAIL" ]
will work just as well, be more portable, probably be understood by more readers, and is not longer to type? – Celada Mar 28 '16 at 11:06