Reputation: 721
I am attempting a bash script to run several git commands in sequence to update a repository. The command I concatenate at the end works if I manually input it into a terminal, but inside the bash script it doesn't do anything. What is the bash syntax error I am making?
cmd1="cd $myGitRepo"
cmd2="git add --all"
cmd3="git commit -m \"test commit msg\""
cmd4="git push"
cmd="$cmd1 && $cmd2 && $cmd3 && $cmd4"
echo "$cmd"
$cmd
Upvotes: 0
Views: 484
Reputation: 489908
When faced with a problem like this, use the debug tools, such as the echo debugger, or the -x
flag:
bash-3.2$ cmd="echo foo && echo bar"
bash-3.2$ $cmd
foo && echo bar
bash-3.2$
This shows that &&
is not treated as syntax when it is the result of a shell variable. Equivalently:
bash-3.2$ set -x
bash-3.2$ $cmd
+ echo foo '&&' echo bar
foo && echo bar
bash-3.2$
The -x
flag tells the shell to print out each command, preceded by the +
marker, before running it.
(You could get this treated as syntax by adding eval
in front, but in general this is not a very good plan.)
Is there some reason not to just write the actual commands you want done, e.g.:
cd $myGitRepo && git add --all && git commit -m "test commit msg" && git push
as the body of your script?
If you want to automatically exit after a failing command, sh and bash both support set -e
; bash gives this the additional name errexit
(as a -o
option). So set -e
tells the shell to exit immediately if any of the simple commands fail:
set -e
cd $myGitRepo
git add --all
git commit -m "test commit msg"
git push
(To end -e
behavior, simply set +e
.)
Upvotes: 2