Wayne Wei
Wayne Wei

Reputation: 3267

How to monitor a shell command running state and auto re-run it once the command end up with error?

I am trying to fulfill a logic like this in shell:

command 1  #a command will run for a long time, but sometimes it could be interrupted by error.

if [[ $? != 0 ]]  #if command 1 failed with return value other than 0
then
    clear command #trigger clear command
    command 1   #and re-run command 1
fi

But this block only can detect 1 round of error for command 1, if in the re-run error happens again, the thread will end up with error.

How to fulfill continuous monitoring on command 1's state and always trigger clear command + re-run command 1 once error happens?

(It is kind of like goto in bat script, but after some digging there is no such thing in shell script...)

Upvotes: 2

Views: 183

Answers (1)

Inian
Inian

Reputation: 85580

You can do this in a while loop and run the command directly in the action block, that way the loop can run based on the exit code the command returns. Using a simple negation ! operator, we can invert the exit code which means the body of the loop gets executed only if the command is failing and will continue to run, till the point when the command is successful

while ! command ; do
    clear command
done

Upvotes: 1

Related Questions