#!/bin/sh
LOG='log --pretty=format:"%h - %an, %ar : %s"'
git $LOG
I expect this to output an actual git log in the specified format. However, all I get is a fatal argument error.
I have also tried the options below, and they also do not work:
LOG="log --pretty=format:\"%h - %an, %ar : %s\""
LOG='log --pretty=format:\"%h - %an, %ar : %s\"'
However, strangely the script below DOES work, and I don't understand why:
LOG='--pretty=format:"%h - %an, %ar : %s"'
git log "$LOG"
It has been argued that shell is considering the variable to be only one argument, however the following works fine:
LOG1LINE='log --pretty=oneline'
git $LOG1LINE
-
2I'm trying to put a command in a variable, but the complex cases always failglenn jackman– glenn jackman2013年07月23日 17:40:05 +00:00Commented Jul 23, 2013 at 17:40
2 Answers 2
Here is one way to overcome this problem. Using bash arrays:
#!/bin/bash
#It's important to use bash instead of sh for this to work
LOG=(log --pretty=format:"%h - %an, %ar : %s")
git "${LOG[@]}"
7 Comments
declare -a LOG=(b).echo $SHELLecho $SHELL results in: /bin/bashThis is a product of how the shell handles arguments.
The first thing the shell does is substitute variables. Quotes that were used in the variable definition are not preserved here. Then it chunks them into arguments, based on either quotes or, if these are not present, word boundaries. Quotes that were quoted when they were first used are escaped at that time, and consequently cannot define word boundaries.
Consequently, the arguments passed to git in your first example are:
log--pretty=format:"%h-%an,%ar:%s"
In the later example, the arguments passed to git are:
log--pretty=format:"%h - %an, %ar : %s"