相关文章推荐
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

In REG=true , 'true' is a string. When you do $REG , you're executing the command true .

if $REG -a $VIN means "run the command true with the option '-a' and argument '$VIN', which are ignored by true. So it's the same as if you had if true .

if $REG && $VIN causes 'true' and 'false' to be executed and their results 'and-ed', which yields false.

if [ "$REG" -a "$VIN" ] DOES NOT WORK (as defined here). This is the same as if test "true" -a "false" . Any non-null string is true, so this statement is true. Same goes for if [[ "$REG" && "$VIN" ]]

However:

if [[ `$REG` && `$VIN` ]] # works

does work because here you execute the commands true and false.

It is always tricky. I recommend the read of pages like wiki.bash-hackers.org/syntax/ccmd/conditional_expression – fedorqui Jan 14, 2014 at 14:57 Neither [[ "$REG" && "$VIN" ]] nor [ "$REG" -a "$VIN" ], because they both check the strings "$REG" and "$VIN" to see if they're nonblank -- that is, they consider "true" and "false" to both be true (nonblank). – Gordon Davisson Jan 14, 2014 at 16:57 @fedorqui: Yes, if $REG && $VIN; works because it treats the two strings as commands; true is actually a command that always succeeds, false is a command that always fails, and the && makes a compound command that succeeds only if both individual commands succeed. This is what you want. – Gordon Davisson Jan 14, 2014 at 17:02

This is the most correct and safe way (unlike executing your $REG and $VIN as other answers suggest). For example, what is going to happen if $REG variable is empty? Or what if it equals to something different than just true or false?

If you want boolean behavior in bash, then consider the fact that empty strings are falsy.

REG=1
if [[ $REG ]]; then
    echo '$REG is true!'

or like that for multiple variables:

REG=1
VIN=''
if [[ $REG && $VIN ]]; then
    echo '$REG and $VIN are true!'
if [[ $REG && ! $VIN ]]; then
    echo '$REG is true and $VIN is false!'

So, if you want something to be false, then either leave it unset or use an empty string.

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.

 
推荐文章