Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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"
echo "False"
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"
echo "False"
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"
echo "False"
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?
–
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"
echo "False"
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...
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.