How to do an if statement from the result of an executed command
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
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.
Even more simple,
netstat -lntp | grep ':8080.*java' > /dev/null && command
If you just want to do one thing.