Monday, May 6, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  145] [ 0]  / answers: 1 / hits: 196149  / 2 Years ago, mon, november 29, 2021, 8:22:53

I have a script where it checks whether a package is installed or not and whether the port 8080 is being used by a particular process or not. I am not experienced at all with bash, so I did something like this:



if dpkg -s net-tools; then
if netstat -tlpn | grep 8080 | grep java; then
echo "Shut down server before executing this script"
exit
fi
else
echo "If the server is running please shut it down before continuing with the execution of this script"
fi

# the rest of the script...


However when the script is executed I get both the dpkg -s net-tools and the netstat -tlpn | grep 8080 | grep java outputs in the terminal, and I don't want that, how can I hide the output and just stick with the result of the ifs?



Also, is there a more elegant way to do what I'm doing? And is there a more elegant way to know what process is using the port 8080 (not just if it's being used), if any?


More From » bash

 Answers
0

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

[#24904] Wednesday, December 1, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ongdiligenc

Total Points: 452
Total Questions: 111
Total Answers: 107

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
ongdiligenc questions
Wed, Apr 13, 22, 10:34, 2 Years ago
Tue, Jun 7, 22, 00:54, 2 Years ago
Sat, Aug 7, 21, 00:37, 3 Years ago
Sat, May 22, 21, 03:06, 3 Years ago
Tue, Mar 1, 22, 10:05, 2 Years ago
;