I've read in online articles that non-designated variables or variables set to null, like VAR= and nothing after it, can still be treated as being real. All you need to do is put the $ in font, making it $VAR.
But it seems there is an exception to this rule, and it involves the testing of a condition using paired '[]' or '[[]]'. The errors reported are bit of any help either. You get and error that reads ' [[: not found ' and what does that really tell you? By a steady process of elimination, and lots of on-line checking to make sure my code looked good, I worked it out:
[ $a != $b ], [[ $a -ne $b ]],
with or without the 'if ... fi' structure will fail if either $a or $b evaluates by bash to be null. If it does, it is apparently removed as an argument. Say either $a and/or $b was non-declared or set to null. for the test conditions, what is passed appears like this:
[ != $b ], [[ -ne $b ]]
[ $a != ], [[ $a -ne ]]
[ != ], [[ -ne ]]
To deal with this, you can wrap either or both variables in a double-quote pair, so that what the rext condition is not a null, though it may evaluate to a null eventually in the next phase:
[ "$a" != "$b" ], [[ "$a" -ne "$b" ]]
might become
[ $a != $b ], [[ $a -ne $b ]]
and
[ "$a" != "$b" ], [[ "$a" -ne "$b" ]]
might become
[ $a != $b ], [[ $a -ne $b ]]
while
[ "$a" != "$b" ], [[ "$a" -ne "$b" ]]
might become
[ $a != $b ], [[ $a -ne $b ]]
I say "might become", because this is not a sure thing. What if instead of $a and/or "$b", you were passing an empty string or space-filled string as a constant? Stripping off the outer double-quote pair,
[ "$a" != "" ] would become [ $a != ]
[[ "$a" -ne "" ]] would become [[ $a -ne ]]
if enclosed spaces, this is what you would see:
[ "$a" != " " ] would become [ $a != ]
[[ "$a" -ne " " ]] would become [[ $a -ne ]]
which is effectively the same thing, because extra whitespaces don't count.
So, we have a problem with some cases of using double-quote pairs, and I don't know how to resolve the conflict that ensues. Avoiding the use of null or spaced constants in test conditions would be one way I suppose. but I've not read anything about limitations such as this.
Aucun commentaire:
Enregistrer un commentaire