0

I made a script to check tnsping but the if statement does not working properly. The following is the script:

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".

-n = The length of STRING is greater than zero

2 Answers 2

4

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 }')
Sign up to request clarification or add additional context in comments.

Comments

2

Neither the $ping variable nor awk are necessary, since grep can return an exit code to if:

if tnsping oracle1 | grep --quiet OK
then
   echo "OK"
else
   echo "NOT OK"
fi

2 Comments

This is correct, but that is only because awk squeezes spaces and <space><space>OK will put OK in $1. If OP was printing $2 it would not be possible.
@andlrc, well-taken pointers on the value of carefulness are useful. However, for my non-awk answer, awk's behavior is irrelevant, and the OP was not printing $2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.