我在理解如何read
从控制台“读取”信息而不是用户输入时遇到问题。有效地“获取线路”?从控制台。
这是我的场景。我将发送echo "information" | ncat "IP" "PORT"
到位于网络内部的端口,运行守护程序以捕获正确的信息。
如果我发送的信息不正确,我将收到一条预定义消息,告诉我发送的信息不正确并重试。但是,如果信息正确,我将得到不同的响应,我不知道响应是什么。
这是我迄今为止尝试过的 BASH 脚本的片段。
if [[read -r line ; echo "$line" ; while "$line" == "Information wrong try again!"]] ; continue
elif [[read -r line ; echo "$line" ; while "$line" != "Information wrong try again!"]] ;break
我对 bash 很陌生,所以我使用的语法可能不正确。
答案1
恐怕你的语法全错了。我想你正在寻找这样的东西:
if [ "$line" = "Information wrong try again!" ]; then
echo "Try again"
else
echo "All's well"
fi
当然,详细信息取决于您运行脚本的方式。如果您希望它成为一个无限循环并重新运行该echo "information" | ncat "IP" "PORT"
命令直到它起作用,您需要如下所示:
line=$(echo "information" | ncat "IP" "PORT")
while [ "$line" = "Information wrong try again!" ]; do
line=$(echo "information" | ncat "IP" "PORT")
sleep 1 ## wait one second between launches to avoid spamming the CPU
done
## At this point, we have gotten a value of `$line` that is not `Information wrong try again!`, so we can continue.
echo "Worked!"
或者,类似地:
while [ $(echo "information" | ncat "IP" "PORT") = "Information wrong try again!" ]; do
sleep 1 ## wait one second between launches to avoid spamming the CPU
done
## rest of the script goes here
echo "Worked!"