linux循环执行命令的shell(bash)脚本直到成功时才停止

实现功能

按照指定的命令列表依次执行。
需要循环执行前面加上loop_exe后既可以循环执行(直到命令执行成功,才会停止)

使用方法
  1. 新建.sh文件,并将下面的代码复制进去
  2. 修改main函数部分代码
    1. loop_exe函数会循环执行知道命令知道成功为止
    2. 传参为所想要执行的命令(用双引号包起来)
  3. 给脚本执行权限chmod a+x xxx.sh / chmod 777 xxx.sh
  4. 执行脚本
#!/bin/bash
# Author: wanghan
# Created Time : Tue 17 Jul 2018 07:35:49 PM CST
# File Name: init.sh
# Description:

function loop_exe()
{
    local ex_count=0
    CMDLINE=$1
    while true ; do
        #command
        sleep 1
        echo The command is \"$CMDLINE\"
        ${CMDLINE}
        if [ $? == 0 ] ; then
            echo The command execute OK!
            break;
        else
            (( ex_count = ${ex_count} + 1 ))
            echo ERROR : The command execute fialed! ex_count = ${ex_count}.
        fi
    done
}


function main()
{
    echo --- Start ---
    loop_exe "echo This is command list:"
    loop_exe "repo init -u https://android.googlesource.com/platform/manifest"
    loop_exe "repo sync -j4"
    echo --- Done ---
}

main

猜你喜欢

转载自blog.csdn.net/daoshuti/article/details/81087965