【问题标题】:shell script check `service httpd restart` command status?shell脚本检查`service httpd restart`命令状态?
【发布时间】:2016-04-02 05:35:01
【问题描述】:

我正在编写一个 shell 脚本,这里是 sn-p ..

sudo service httpd restart   --- ( 1)  

if [ $? -eq 0 ]; then

     # Now configure php.ini using sed command 
     sudo sed -i 's_;date.timezone =_date.timezone = "Asia/Kolkata"_' /etc/php.ini 

  # Now restart the httpd server again 

  sudo service httpd restart  ---- This statement throws error 

当我在上面运行脚本时,我在第二个 sudo service httpd restart 语句处收到错误 Address already in use: make_sock: could not bind to address

我怀疑这是因为当第一次运行 sudo service httpd restart 时,在它完成完全第二次“sudo service httpd restart”运行之前。

那么我怎样才能确定地测试如果第一个sudo service httpd restart 完成,那么只有其余的代码会执行。

我希望我可以理解..

谢谢

【问题讨论】:

    标签: linux apache shell unix sh


    【解决方案1】:

    忘记[ 给予:

    if sudo service http restart; then
        # stuff
        if sudo service http restart; then
            echo ok
        else
            # error handling for second service failure
        fi
    else
        # error handling for first failure
    fi
    

    如果返回状态为零,则命令为真,否则为假。 Shell 命令也必须在调用下一行之前终止。

    原则上,service 有可能在后台执行操作并在完成前退出。在实践中,这并不是因为这真的会把事情搞砸。

    【讨论】:

      【解决方案2】:

      不确定命令是否为背景。如果是这样,您可以检查您的命令是否仍在进程列表中:

      // ... your code ...
      c=1
      while [[ c -gt 0 ]] 
      do
          c=`ps l | grep -c "service httpd restart"`
      done
      service httpd restart 
      

      【讨论】:

      • 如果service命令不在后台,那么if []语句是否会在httpd完全重启时返回0?
      • 不,这样它只会检查命令是否仍在运行。如果它完成(无论哪种方式),while 循环将结束,下一次重新启动将发生。如果您需要处理错误,@msw 肯定已经发布了更好的解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-01
      • 1970-01-01
      • 2013-01-05
      • 2016-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多