I am trying to accept a quoted parameters in bash similar to:
$ git commit -m "message as a sentence"
or
$ something "foo bar"
And from that, I would like to extract message as a sentence
and foo bar
.
What I have done so far is:
if [[ "$2" =~ "-m" ]]; then
if [ -z $3 ]; then
echo "Must have a message"
else
# @TODO
fi
fi
Any ideas?
Continuing from the comment, what happens on the command line regarding the arguments to your script is handled by your shell. So when you provide command line arguments the normal shell expansions and word-splitting apply. When you quote arguments to your script, your shell will properly avoid word-splitting within quotes, but the actual quotation marks themselves will be removed by your shell.
Within your script, your positional parameters will properly contain the results of your shell's handling of the arguments. So in your case, your script (or git
in your example) will receive,
$1 : commit
$2 : -m
$3 : your message as a sentence
Your script logic is fine, the problem your are running into in your script is improper quoting. Specifically [[ ... ]]
does not require quoting, but [ ... ]
does.
Since you do not quote $3
in [ -z $3 ]
you effectively are asking:
[ -z your message as a sentence ]
which the shell will take as too many arguments. So to remedy the problem, quote when using test
or [ ... ]
(which are synonymous), e.g.
[ -z "$3" ]
Looks things over and let me know if you have further questions.