Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am trying to do an IF statement from the output of an executed commmand. Here is how I am trying to do it, but it doesn't work. Does anyone know the right way to do this?

if [ "`netstat -lnp | grep ':8080'`" == *java* ]; then
  echo "Found a Tomcat!"
fi
share|improve this question
add comment

4 Answers 4

up vote 6 down vote accepted

Use the bash [[ conditional construct and prefer the $(<command>) command substitution convention. Additionally, [[ prevents word splitting of variable values therefore there is no need to quote the command substitution bit..

if [[ $(netstat -lnp | grep ':8080') == *java* ]]; then
  echo "Found a Tomcat!"
fi
share|improve this answer
1  
Thanks. That was really helpful and educational. I appreciate it. –  djangofan Oct 24 '12 at 17:10
add comment

Another alternative is to simply test the exit status of grep itself, which will return false (1) if there was no match and true (0) if there was one, by not using the [ command.

if netstat -lntp | grep ':8080.*java' > /dev/null; then
    echo "Found a Tomcat!"
fi

The redirection to /dev/null is to prevent it from also printing the found line to the screen.

share|improve this answer
    
Great advice. Thanks. –  djangofan Oct 24 '12 at 20:51
1  
Note the -q option to grep instead of redirecting to /dev/null. With -q, grep doesn't output anything and stops searching after the first match. –  Stéphane Chazelas Oct 24 '12 at 22:37
add comment

You can do more precise, yet simple, matching with awk.

if netstat -lnp | awk '$4 ~ /:8080$/ && $7 ~ /java/ {exit(0)} END {exit(1)}'; then …

To match the structure of your command more closely, the portable way of doing wildcard matching on a string in a shell is with the case construct.

case "$(netstat -lnp | grep ':8080')" in
  *java*)  echo "Found a Tomcat!";;
esac
share|improve this answer
add comment

Even more simple,

netstat -lntp | grep ':8080.*java' > /dev/null && command

If you just want to do one thing.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.