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?
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?
test if "$x" is not empty
if [ -n "$x" ]; then
...
else
...
fi
test if "$x" is empty (has a length of zero) :
if [ -z "$x" ]; then
...
else
...
fi
or (if $x has a length of zero)
if [ ${#x} -eq 0 ]; then
...
else
...
fi
# 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 :
[[ -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)
Thank you, it works :}
Here is a tricky example here is the code :
mytst(){
a=${1-whatever}
echo $a
}
Now let's run the code ...
If you understand every result, then you got how it works ...
# 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.)