沉默/dev/tcp/host/port重定向错误 [英] Silence /dev/tcp/host/port redirection errors
问题描述
以下脚本将测试从8079到8081的tcp端口是打开还是关闭.
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
输出
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:~$
如何删除以下几行?我曾尝试将stderr重定向到/dev/null
,例如 2>/dev/null
,但是没有用.
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
所需的输出
user@linux:~$ ./script.sh
port 8079 is closed
port 8080 is open
port 8081 is closed
user@linux:~$
推荐答案
我试图将stderr重定向到/dev/null,如2>/dev/null一样,但是没有用.
I've tried to redirect stderr to /dev/null like 2>/dev/null but didn't work.
实际上是可行的.只是您需要重定向整个循环的stderr * ,而不仅仅是重定向 echo
的stderr * .因为不是 echo
报告这些错误.例如:
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
* 或if块,或 echo
范围之外的任何内容.无论是标准手册还是bash手册都没有明确说明其工作原理,我想这只是常识.
* 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.
这篇关于沉默/dev/tcp/host/port重定向错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!