问题
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:~$
回答1:
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.
来源:https://stackoverflow.com/questions/61966798/silence-dev-tcp-host-port-redirection-errors