Joao  Vitorino Joao Vitorino - 5 months ago 6
Bash Question

bash script if statment

I made a script to check tnsping but the if does not working properly

ping=$(tnsping oracle1 |grep OK| awk -F" " '{print $1 }')

if [ -n $ping ]
then
echo "OK"
else
echo "NOT OK"
fi


If a execute change oracle for a non-existing oracle server I also receive "OK".

Probably is a silly mistake that I can't find what is it.

# -n = The length of STRING is greater than zero

Answer

Wrap double quotes around $ping:

if [ -n "$ping" ]
then
   echo "OK"
else
   echo "NOT OK"
fi

Or it will undergo word splitting and globbing and resolve in the following arguments for [: '-n' and ']' when $ping is empty. which is the same as:

 if [ '-n' '-n' ']'

See man test:

-n STRING
the length of STRING is nonzero
STRING
equivalent to -n STRING

-z STRING
the length of STRING is zero


And FYI you can omit the call to grep and use awk directly. And since the default Field Separator (-F) is space that can be omitted as well:

ping=$(tnsping oracle1 | awk '/OK/{print $1 }')