Reputation: 41
I am studying a simple bash script, or what I thought would be simple. It looks as though it is simply trying to store the first argument as a variable before proceeding.
However, it fails every time.
Script:
while [ $# -gt 0 ]; do
case "$1" in
variableName=*)
variableName="${1#*=}"
;;
*)
echo "***************************"
echo "* Invalid argument:"
echo "* ($1)"
echo "***************************"
exit 1
esac
shift
done
Now, if I try to execute it, this happens:
$ sh script.sh "test"
***************************
* Invalid argument:
* (test)
***************************
The pattern match is *
, so that looks like it should match anything. At that point, it should simply be storing the variable, and that's it.
In the non-dissected script, there are other variables being stored which proceed this one, hence the loop.
Upvotes: 1
Views: 293
Reputation: 532418
Your pattern is variablename=*
, not *
. Your argument doesn't start with variablename=
, so that case fails.
Upvotes: 0
Reputation: 1711
If you run your code with the argument variableName=xx
it will not go into the Invalid argument condition.
Add a echo foo
in the line above the ;;
and you will see this.
In the end of the script, the variable variableName
will be set to the value you passed in, i.e. xx
in this case.
The following snipped is your code plus some echo statements which hopefully clearly show, what's going on.
while [ $# -gt 0 ]; do
case "$1" in
variableName=*)
variableName="${1#*=}"
echo "setting variableName to $variableName"
;;
*)
echo "***************************"
echo "* Invalid argument:"
echo "* ($1)"
echo "***************************"
exit 1
esac
shift
done
echo "variableName is set to $variableName"
Upvotes: 1