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