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 this, 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.
To invoke a function, simply use the function name as a command. To pass parameters to the function, add space separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3 etc.
To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 … To pass multiple arguments to a shell script you simply add them to the command line: # somescript arg1 arg2 arg3 arg4 arg5 …
You can handle command-line arguments in a bash script in two ways. One is by using argument variables, and another is by using the getopts function.
$() Command Substitution According to the official GNU Bash Reference manual: “Command substitution allows the output of a command to replace the command itself.
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 of asdfzxcv
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With