LaVOZs

The World’s Largest Online Community for Developers

'; bash - Silence /dev/tcp/host/port redirection errors - LavOzs.Com

The following script will test if tcp port from 8079 to 8081 is open or closed.

for port in {8079..8081}; do
  echo >/dev/tcp/127.0.0.1/$port &&
    echo "port $port is open" ||
    echo "port $port is closed"
done

Output

user@linux:~$ ./script.sh 
./script.sh: connect: Connection refused
./script.sh: line 2: /dev/tcp/127.0.0.1/8079: Connection refused
port 8079 is closed
port 8080 is open
./script.sh: connect: Connection refused
./script.sh: line 2: /dev/tcp/127.0.0.1/8081: Connection refused
port 8081 is closed
user@linux:~$ 

How do I remove the following lines? I've tried to redirect stderr to /dev/null like 2>/dev/null but didn't work.

./script.sh: connect: Connection refused
./script.sh: line 2: /dev/tcp/127.0.0.1/8079: Connection refused

Desired Output

user@linux:~$ ./script.sh 
port 8079 is closed
port 8080 is open
port 8081 is closed
user@linux:~$ 

I've tried to redirect stderr to /dev/null like 2>/dev/null but didn't work.

Actually it works. It's just you need to redirect the whole loop's stderr*, not just echo's; as it's not echo that reports those errors. E.g:

for port in {8079..8081}; do
  if echo >/dev/tcp/127.0.0.1/$port; then
    echo "port $port is open"
  else
    echo "port $port is closed"
  fi
done 2>/dev/null

* Or the if block, or whatever beyond the scope of echo. Neither the standard nor bash manual makes an explicit remark on why this works, I guess it's just common sense.

Related
Spawning an interactive telnet session from a shell script
Getting an “ambiguous redirect” error
How can I get rid of this osascript output?
Java.lang.Process redirect errorstream to /dev/null
Writing outputs to log file and console
Port listen using /dev/tcp
How to suppress error from a single line of script
Capture output of error in bash exec I/O redirection
Can I pipe lshw warnings to /dev/null when I run it as a standard user?