[SOLVED] Linux: How to stop executing chain of commands if one fails

amfzn

New Member
Joined
Mar 30, 2021
Messages
8
Reaction score
1
Credits
106
Hello, on Linux command line GNU bash, version 5.0.17

When i execute command like mv a b;rm b

How to do it so the "rm b" command is not executed if "mv a b" returns an error?

I have tried to apped "||exit" after "mv a b", but that quits the SSH session.

Thank You
 


Untested, but && might be what you're after. That only executes the command if the previous command had an exit code of zero - meaning successfully completed.

So:

Code:
mv a b && rm b
 
Hmm... is that right?

command 1 && command 2
would run these two commands simultaneously before command 1 ends.

however...

command 1 || command 2
runs these commands serially, if commands 1 dies before finishing, command 2
will not run.

To test this run some command that takes a while to execute
ls -R /* >> /home/myfile.txt && tail -f myfile.txt

Notice you can watch the txt file grow as the first command is still being executed.

However I've noticed some commands will wait.

sleep 5 || echo "I'm done"
sleep 5 && echo "I'm done"

behave identically.
 
Last edited:
command 1 && command 2
would run these two commands simultaneously before command 1 ends.


No, that would be the case with one &

"&&" is used to chain commands together, such that the next command is run if and only if the preceding command exited without errors (or, more accurately, exits with a return code of 0). "-" is a command line argument with no specific bash function.

Reference from serverfault.com

Cheers

Wiz

The use of the double & I have seen as making it "conditional"
 
Hmm... is that right?

Yes... I'm pretty sure...

Try "sudo apt update && sudo apt upgrade -y && sudo apt clean -y" for example.
 
Thanks for help!, this works:
mv a b && rm b

This does not:
mv a b & rm b
mv a b;rm b
mv a b || rm b

working = second command is not executed in case first fails
 
I figured that's what you were asking for. The && operand is a pretty handy one to have in your toolbox, as it only continues (ideally) if the first command was successful.
 

Members online


Latest posts

Top