Silence /dev/tcp/host/port redirection errors

跟風遠走 提交于 2021-02-19 06:01:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!