Bash: passing script arguments

I have a number of commands that I run before executing a git project, so I 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 

waiting for the message to be sent to the script

 $ ./dostuff_then_commit "my message" 

When I do it, I get it

 fatal: Paths with -a does not make sense. 

because $1 defined, but the message is not transmitted correctly? Can someone see the problem and / or suggest a solution? Thanks, SO.

+6
source share
4 answers

If the message contains spaces, it will expand to several parameters up to git commit . (Pay attention to quoting in another case.) Quote:

 if [ -z "$1" ]; then git commit -a -m "no message" else git commit -a -m "$1" fi 

A few additions:

  • I also quoted the text in [] for a slightly different reason: if the commit message was empty, you will get the diagnostics of missing parameters from [ . Again, quoting this, this avoids this. (Instead, you may want to catch this and force the user to enter a real commit message, although if necessary you will probably get a bunch of asdfzxcv commit messages ...)

  • The error message that you receive is due to the fact that the first message of the commit message is received as a commit message, and the rest are transmitted as specific file names for commit; this, as the error message says, does not make sense when git reports all ( -a ).

+6
source

Try to surround $1 quotation marks - otherwise git considers my message, and message is something else.

 if [ -z $1 ]; then git commit -a -m "no message"; else; git commit -a -m "$1"; fi 
+2
source

I would like to add that you can combine such parameters:

 git commit -am "some message" 
+2
source

you should use "$1" instead of $1 as $ 1`, there may be spaces in it.

with $1 as my message , substituting in:

 git commit -a -m $1 

gives:

 git commit -a -m my message 

a

 git commit -a -m "$1" 

gives:

 git commit -a -m "my message" 
+1
source

Source: https://habr.com/ru/post/891512/


All Articles