Hiding output of a command
To hide the output of any command usually the stdout
and stderr
are redirected to /dev/null
.
command > /dev/null 2>&1
Explanation:
1.command > /dev/null
: redirects the output of command
(stdout) to /dev/null
2.2>&1
: redirects stderr
to stdout
, so errors (if any) also goes to /dev/null
Note
&>/dev/null
: redirects both stdout
and stderr
to /dev/null
. one can use it as an alternate of /dev/null 2>&1
Silent grep
: grep -q "string"
match the string silently or quietly without anything to standard output. It also can be used to hide the output.
In your case, you can use it like,
if dpkg -s net-tools > /dev/null 2>&1; then
if netstat -tlpn | grep 8080 | grep java > /dev/null 2>&1; then
#rest thing
else
echo "your message"
fi
Here the if conditions will be checked as it was before but there will not be any output.
Reply to the comment:
netstat -tlpn | grep 8080 | grep java > /dev/null 2>&1
: It is redirecting the output raised from grep java
after the second pipe. But the message you are getting from netstat -tlpn
. The solution is use second if
as,
if [[ `netstat -tlpn | grep 8080 | grep java` ]] &>/dev/null; then
lsof -i :<portnumnber>
should be able to do something along the lines of what you want.
While flushing the output to /dev/null
is probably the easiest way, sometimes /dev/null
has file permissions set so that non-root cannot flush the output there. So, another non-root way to do this is by
command | grep -m 1 -o "abc" | grep -o "123"
This double-grep
setup finds the matching lines with abc
in them and since -o
is set ONLY abc
is printed and only once because of -m 1
. Then the output which is either empty or abc
is sent to grep to find only the parts of the string which match 123
and since the last command only outputs abc
the empty string is returned. Hope that helps!