IF $ has value then?


 
Thread Tools Search this Thread
Top Forums UNIX for Dummies Questions & Answers IF $ has value then?
# 1  
Old 01-07-2011
IF $ has value then?

Hello,

I was wondering if there is any way to declare something like this pseudo code:

If [$x HAS A VALUE OR IS NOT EMPTY] ;then?

how to write to check if that $x has a value or anything?
# 2  
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:
# 3  
Old 01-07-2011
Thank you, it works :}
# 4  
Old 01-07-2011
Here is a tricky example here is the code :
Code:
mytst(){
a=${1-whatever}
echo $a
 }

Now let's run the code ...
If you understand every result, then you got how it works ...
Code:
# mytst
whatever
# mytst 1
1
# mytst 2
2
# mytst ""

# mytst
whatever
# mytst If no arg is given set a to whatever
If
# mytst "If no arg is given set a to whatever"
If no arg is given set a to whatever
# mytst "          "

# mytst ""

# mytst
whatever
#

By the way, you should carefully read this (you may find the "Syntax of String Operator" section useful.)

Last edited by ctsgnb; 01-07-2011 at 02:04 PM..
This User Gave Thanks to ctsgnb For This Post:
 
Login or Register to Ask a Question

Previous Thread | Next Thread
Login or Register to Ask a Question