问题:
将命令结果存储在变量中portcheck
无法按预期工作。我的脚本包含这个方法
#!/bin/bash
...
status() {
portcheck=$(nc -z -v -w5 localhost 8443)
echo "*${portcheck}*"
if [[ $portcheck == *refused* ]]; then
echo "Application is stopped"
elif [[ $portcheck == *succeeded* ]]; then
echo "Application is started"
else
echo "state unknown"
fi
}
当我执行 myscript 时,我得到以下结果:
> $ ./myscript status
> Connection to localhost 8443 port [tcp/*] succeeded!
> **
> state unknown
但我想要的是命令的结果存储在变量中portcheck
并且输出应该看起来像
> $ ./myscript status
> Connection to localhost 8443 port [tcp/*] succeeded!
> *Connection to localhost 8443 port [tcp/*] succeeded!*
> Application is started
我根据以下方法尝试了几种变体 https://stackoverflow.com/questions/4651437/how-to-set-a-variable-to-the-output-from-a-command-in-bash 和其他例如
portcheck=`nc -z -v -w5 localhost 8443`
代替
portcheck=$(nc -z -v -w5 localhost 8443)
但这没有用。我究竟做错了什么?
背景:
命令
nc -z -v -w5 localhost 8443
检查端口是否可连接。它返回
Connection to localhost 8443 port [tcp/*] succeeded!
如果端口是“开放”并且
nc: connect to localhost port 8443 (tcp) failed: Connection refused
如果端口“关闭”。
如果我只是在 bash 中简单地执行命令,那么效果很好。
答案1
该nc
调用基本上打印到 stderr,您需要将输出发送到 stdout,如下所示:
portcheck=$(nc -z -v -w5 localhost 8443 2>&1)
echo "*${portcheck}*"
在本例中,这将是输出:
*Connection to localhost 8443 port [tcp/*] succeeded!*