run command until successful n times bash

人盡茶涼 提交于 2021-02-10 20:51:58

问题


I want to run a command n number of times if it returns unsuccessful I have started with the below loop

until find . -type f -exec md5sum {} \;
do
<something >
done

I want to run the about n times before it goes continues to the next file Not sure how I can continue from here. I have tried using the return variable $? and looping using this but had no luck Also how could I use the above loop or what is proposed here to put the output of the find into a variable thanks

Let me make this abit clearer

so I'm actually running like this with a function

fcn () {

    for file
    do
     until md5sum "$file"
        do
        <something >
        done
    done
}

Calling with

find . -type f -print0 | xargs -0 -P 0 bash -c 'fcn "$@"'

So the return value of md5sum "$file" is the one I have looked into


回答1:


attempts=0
while ! result=$(find . …) || (( attempts++ > 5 )); do
    …
done

The above will set the results of the successful find command into the variable result. If attempts exceeds five, then the loop will end, but the value of result is unclear if that happens.




回答2:


You can check the result of a command in the environment variable $?

This variable will hold the value 0 if the last command executed was successful.

My guess would be something like this:

while true; do
    $(command)
    if [ $? -eq 0 ] ; then
        exit
    fi
done

Remember that if anything is executed AFTER your command, the value of $? will change. So just make sure whenever you execute the command in question here, save $? value in another variable or check it immediately.



来源:https://stackoverflow.com/questions/30197818/run-command-until-successful-n-times-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!