相关文章推荐
文武双全的企鹅  ·  SSL Medium Strength ...·  2 月前    · 
高大的山羊  ·  Excel 有哪些和 vlookup ...·  6 月前    · 
玩命的苦瓜  ·  Java ...·  1 年前    · 
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?

Use get config --type bool --get myvalue to ensure that you actually get a result of true or false, rather than a possible synonym. – chepner Jan 25, 2020 at 14:26

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...

Also, --type bool should be passed to ensure that you get back true, rather than possibly yes (which would trigger a false negative for the suggested code and an infinite loop leading to memory exhaustion for the second). – chepner Jan 25, 2020 at 14:27

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.