问题
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