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

amfzn

New Member
Joined
Mar 30, 2021
Messages
7
Reaction score
1
Credits
89
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
 


KGIII

Super Moderator
Staff member
Gold Supporter
Joined
Jul 23, 2020
Messages
5,762
Reaction score
5,196
Credits
46,519
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
 

dos2unix

Well-Known Member
Joined
May 3, 2019
Messages
1,318
Reaction score
948
Credits
7,826
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:

wizardfromoz

Administrator
Staff member
Gold Supporter
Joined
Apr 30, 2017
Messages
7,112
Reaction score
5,989
Credits
23,530
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"
 

KGIII

Super Moderator
Staff member
Gold Supporter
Joined
Jul 23, 2020
Messages
5,762
Reaction score
5,196
Credits
46,519
Hmm... is that right?

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

Try "sudo apt update && sudo apt upgrade -y && sudo apt clean -y" for example.
 
OP
A

amfzn

New Member
Joined
Mar 30, 2021
Messages
7
Reaction score
1
Credits
89
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
 

KGIII

Super Moderator
Staff member
Gold Supporter
Joined
Jul 23, 2020
Messages
5,762
Reaction score
5,196
Credits
46,519
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.
 
$100 Digital Ocean Credit
Get a free VM to test out Linux!

Staff online


Top