V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
vnex
V2EX  ›  问与答

bash while 的 exit status

  •  
  •   vnex · 2020-03-03 00:14:33 +08:00 · 930 次点击
    这是一个创建于 1519 天前的主题,其中的信息可能已经有所发展或是发生改变。

    下面的 bash 脚本:

    echo "try to ping ${DB_HOST}: ${DB_PORT}";
    while ! nc -z ${DB_HOST} ${DB_PORT}; do
      echo "try to ping ${DB_HOST}: ${DB_PORT} fail";
      sleep 3;
    done
    

    nc -z ${DB_HOST} ${DB_PORT} 成功连同远程主机的时候,返回值 是 0, 然后 前面加个 , 返回值变成1, 不就变成 连同后,无限次尝试下去

    我看了下 bash 的文档

    Execute consequent-commands as long as test-commands has an exit status of zero. The return status is the exit status of the last command executed in consequent-commands, or zero if none was executed.
    

    while 的条件是 0 的时候,才执行 do 里面的语句,感觉有点奇怪,找大伙确认下

    谢谢

    3 条回复    2020-03-03 15:17:08 +08:00
    fengtons
        1
    fengtons  
       2020-03-03 00:33:32 +08:00 via Android
    没错,在 shell 返回 0 代表成功,所以会执行 do 后面的命令。
    你的 while 语句的格式需要这样写:
    while [ ! $(nc -z ${DB_HOST} ${DB_PORT}) ]; do
    mayx
        2
    mayx  
       2020-03-03 00:58:26 +08:00 via Android
    不习惯的话用 until 也可以吧
    ps1aniuge
        3
    ps1aniuge  
       2020-03-03 15:17:08 +08:00
    18317powershell 学习群 3532
    powershell 在 win,linux 通用,它严谨,它强类型变量=对象,它是 linux 脚本的未来。

    你脚本出问题,老板罚款 50,你会选择 bash,
    你脚本出问题,老板罚款 500,你会选择 python,
    你脚本出问题,老板罚款 5000,你会选择 linux 版 powershell,

    powershell 可以锁死变量类型,如[string]$a,,,,py 不行。powershell 比 py 更严谨。
    powershell 可以在 win 下通过 vscode+remotessh 模块远程,
    单步,断点,调试 linux 下的 ps1 脚本。生产力比 bash 提升 10 倍,健壮性提升 10 倍。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2644 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:37 · PVG 22:37 · LAX 07:37 · JFK 10:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.