[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,421
Reaction score
5,700
Credits
51,675
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,442
Reaction score
1,048
Credits
8,898
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,296
Reaction score
6,192
Credits
24,868
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,421
Reaction score
5,700
Credits
51,675
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,421
Reaction score
5,700
Credits
51,675
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