Why [[ -n $var ]] instead of [[ $var ]]?
Clash Royale CLAN TAG#URR8PPP
Why [[ -n $var ]] instead of [[ $var ]]?
In this answer I had some code which read:
if [[ $ZSH_VERSION ]]; then
This was edited to be:
if [[ -n $ZSH_VERSION ]]; then
Update: I just saw the edit comment:
[[ x ]] didn't work until recently in zsh
I looked through the zsh
release notes and couldn't find reference to this.
zsh
Which zsh
version first allowed [[ x ]]
?
zsh
[[ x ]]
2 Answers
2
From the zsh
5.5.1 docs for CONDITIONAL EXPRESSIONS
zsh
CONDITIONAL EXPRESSIONS
For compatibility, if there is a single argument that is not syntactically significant, typically a variable, the condition is treated as a test for whether the expression expands as a string of non-zero length. In other words, [[ $var ]] is the same as [[ -n $var ]]. It is recommended that the second, explicit, form be used where possible.
With the source tree around,
% grep -rl 'if there is a single argument' .
./Doc/Zsh/cond.yo
% git blame ./Doc/Zsh/cond.yo | grep 'if there is a single argument'
d082827c83 (Jun T 2014-05-18 22:03:35 +0900 198) For compat...
Inspection of git log
shows that the code change went in a bit earlier than the documentation:
git log
commit 9d47e8398d299e53ffe4e7ddf3731d2fedae9948
...
Date: Tue May 13 08:16:50 2014 -0700
32609: [[ $var ]] behaves as [[ -n $var ]] for bash/ksh compatibility
The mapping of the ChangeLog
file to git tag
is not clear to me, but it appears zsh
5.0.6 (Thu Aug 28 19:07:04 2014 +0100) is the first version with this change.
ChangeLog
git tag
zsh
It is more explicit showing what the code is doing.
Personally, in this case I'd slightly prefer [[ -n $ZSH_VERSION ]]
because it shows that it is testing for non-emptyness of the value of the var.
[[ -n $ZSH_VERSION ]]
But I often have vars meant for boolean meaning in my scripts and I name them accordingly, like is_logged_in
or running_in_background
. If such vars are unset in my scripts they are false
. And in such cases I prefer to use [[ running_in_background ]]
, just because this reads better without the -n
part, like a normal sentence:
is_logged_in
running_in_background
false
[[ running_in_background ]]
-n
if [[ running_in_background ]] ; then
echo "something" | logger -t myprog
fi
But IMO it is just matter of taste, and as such should not have been edited: it's your code.
Well, OP quoted code by another author and that same author then came in and changed it, so "your code" in this particular case means "both their code". ;-) :-)
– Fabby
39 mins ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
See e.g. github.com/zsh-users/zsh/blob/master/ChangeLog#L11593
– Kusalananda
34 mins ago