[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
6,467
Reaction score
5,726
Credits
52,033
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,449
Reaction score
1,055
Credits
8,957
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,320
Reaction score
6,205
Credits
25,047
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
6,467
Reaction score
5,726
Credits
52,033
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
6,467
Reaction score
5,726
Credits
52,033
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!

Linux.org Hosting Donations
Consider making a donation

Members online


Top