bash: passing script arguments
I have a series of commands that I run before committing a git project so I've put it in a bash script. At the end I have a block that does the commit:
if [ -z $1 ]; then git commit -a -m "no message"; else; git commit -a -m $1; fi
with the expectation that the message is passed to the script
$ ./dostuff_then_commit "my message"
When I do th开发者_运维百科is, I get that
fatal: Paths with -a does not make sense.
because $1
has been defined but the message is not passed correctly? Can anyone see the problem and/or suggest a solution? Thanks SO.
If the message contains spaces, it will expand to multiple parameters to git commit
. (Notice the quoting in the other case.) Quote it:
if [ -z "$1" ]; then
git commit -a -m "no message"
else
git commit -a -m "$1"
fi
A couple of addenda:
I also quoted the one in the
[]
, for a slightly different reason: if the commit message were empty, you would get a missing parameter diagnostic from[
. Again, quoting it avoids this. (You might instead want to catch that and make the user enter a real commit message, although if it were that necessary you'd probably get a bunch ofasdfzxcv
commit messages....)The error message you're getting is specifically because the first word of the commit message is taken as the commit message and the rest are passed as specific filenames to commit; this, as the error message states, makes no sense when telling
git
to commit everything (-a
).
Try to surround $1
with quotes - otherwise git thinks my
is the message and message
is something else.
if [ -z $1 ]; then git commit -a -m "no message"; else; git commit -a -m "$1"; fi
I would just like to add that you can combine options like so:
git commit -am "some message"
you should use "$1"
instead of $1 as
$1` can have spaces in it.
with $1
as my message
substituting in:
git commit -a -m $1
gives:
git commit -a -m my message
while:
git commit -a -m "$1"
gives:
git commit -a -m "my message"
精彩评论