sethfri
sethfri

Reputation: 1327

How do I check a git config value in a Bash if/else statement?

I'm trying to read a git config value in a bash script, and conditionally act on it depending on whether it's true or false.

I'd expect to be able to do:

if [ $(git config --get myvalue) ]; then
   echo "True"
else
   echo "False"
fi

However, when I run the above example, True is always printed. Directly comparing the value to true seems to work properly, like so:

if [ $(git config --get myvalue) = true ]; then
   echo "True"
else
   echo "False"
fi

However, most programming languages don't require a direct comparison to a boolean value, so this goes against what I'd expect.

It does actually seem like this works:

if $(git config --get myvalue); then
   echo "True"
else
   echo "False"
fi

My understanding is that putting an expression in [ ] calls the test command under the hood. However, it's not obvious to me why the boolean expression isn't evaluated properly with test.

Why doesn't [ ] evaluate the expression correctly?

Upvotes: 1

Views: 1166

Answers (1)

John Kugelman
John Kugelman

Reputation: 361730

Bash doesn't have boolean variables. true is a string and could be written as "true" or 'true' with no change in semantics. It is normal and correct to explicitly compare it to true or false.

if [[ $(git config --get myvalue) == true ]]; then
   echo "True"
else
   echo "False"
fi

if $(git config --get myvalue); then
   echo "True"
else
   echo "False"
fi

Don't do this. It's a major security vulnerability. What it's really is doing executing whatever command git config outputs. It happens to work because there are commands named true and false which succeed and fail, respectively.

What if that command weren't true or false? What if somebody were to change myvalue to rm -rf /? You'd be having a bad time...

Upvotes: 5

Related Questions