Bash while循环使用包含本地$ variable的远程grep

时间:2018-02-07 11:39:55

标签: linux bash shell ssh while-loop

我想实现以下

  • read nodename
  • 获取用户输入
  • ssh到远程主机和grep -w /path/to/file $nodename
  • 如果找到$ nodename echo "Sorry, hostname already exists, please try again"
  • 获取新的$ nodename
  • 的用户输入
  • 重复直到$ nodename是唯一的

我有什么

echo "Please enter a node name"
read nodename

while ssh remotehost.example.com "grep -w '$nodename' /path/to/file"  
            do
                   echo "Sorry, node name already exists, please try again"
                   read nodename
    done

如果我在promt上运行ssh remotehost.example.com "grep -w '$node' /path/to/file",它会返回正确的答案。但是,当在上面的while循环中运行时,远程文件中的所有内容都会打印到stdout,答案总是要求新的节点名。

我需要更改什么才能使ssh remotehost.example.com "grep -w '$node' /path/to/file"在while循环中工作?

1 个答案:

答案 0 :(得分:0)

尝试下一步:

echo "Please enter a node name"
read nodename

while true
do
    ssh example.com "grep -q ${nodename} /path/to/file"
    status="${?}"
    if [[ ${status} -eq 0 ]]
    then
        echo "Sorry, node name already exists, please try again"
        read nodename
    else break
    fi
done
  • grep -q ... - 安静;不要写任何标准输出。如果发现任何匹配,则立即退出零状态,即使检测到错误也是如此。

  • status="${?}" - 通过ssh命令执行远程命令的退出状态

  • 检查远程命令的status并执行必需的逻辑
  • 利润