Sponsored Content
Full Discussion: IF $ has value then?
Top Forums UNIX for Dummies Questions & Answers IF $ has value then? Post 302486226 by ctsgnb on Friday 7th of January 2011 12:25:53 PM
Old 01-07-2011
test if "$x" is not empty
Code:
if [ -n "$x" ]; then
...
else
...
fi

test if "$x" is empty (has a length of zero) :
Code:
if [ -z "$x" ]; then
...
else
...
fi

or (if $x has a length of zero)

Code:
if [ ${#x} -eq 0 ]; then
...
else
...
fi

Code:
# a=
# [[ ${#a} -eq 0 ]] && echo yes || echo no
yes
# a=x
# [[ ${#a} -eq 0 ]] && echo yes || echo no
no
# a=123
# [[ ${#a} -eq 0 ]] && echo yes || echo no
no
# a=0
# [[ ${#a} -eq 0 ]] && echo yes || echo no
no

You could also consider the following :
Code:
[[ -z "$a" ]] && echo Empty || echo NotEmpty
[[ ! -z "$a" ]] && echo NotEmpty || echo Empty
[[ -n "$a" ]] && echo NotEmpty || echo Empty

In fact the doublequote enclosing the $a are not necessary in [[ ]] (ksh and bash)

Last edited by ctsgnb; 01-07-2011 at 01:45 PM..
This User Gave Thanks to ctsgnb For This Post:
 
All times are GMT -4. The time now is 01:21 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy