I am practicing bash scripting and have a question about && operator
As per O'reily bash cookbook if the command before && operator fails the command that precedes it should cease to execute
See below code
-bash-4.2$ pwd
/home/postgres
-bash-4.2$ mkdir testdir
-bash-4.2$ dir=testdir1
-bash-4.2$ cd $dir1 && rm -rf *
-bash-4.2$ echo $?
0
-bash-4.2$ ls
I expect the rm -rf command to fail as the command cd testdir1 fails, but rm -rf executes and cleans up. The behaviour is more like ";" operator .
Can someone explain please what am i missing
The issue relates to the exit codes.
The && operator will execute the second command if the first one indicates that it was successful.
consider the following:
gmc@linux-ihon:/tmp> rm -rf nonexistant
gmc@linux-ihon:/tmp> echo $? # Note that there is no error message and the exit status is 0 (success).
0
gmc@linux-ihon:/tmp> rm -r nonexistant
rm: cannot remove 'nonexistant': No such file or directory
gmc@linux-ihon:/tmp> echo $? # Note that there was an error message and the exit status is 1 (unsuccessful)
1
gmc@linux-ihon:/tmp>
So now consider the following:
gmc@linux-ihon:/tmp> rm -rf nonexistant && echo "rm success"
rm success
gmc@linux-ihon:/tmp> rm -r nonexistant && echo "rm success"
rm: cannot remove 'nonexistant': No such file or directory
gmc@linux-ihon:/tmp>
In this case, because the rm -rf of the nonexistant directory is deemed successful, the next command is executed. Whereas rm -r of the same directory is deemed a failure, so the next command is not executed.
I'm not sure why rm -f returns success when the directory does not exist, one school of thought is that if the directory doesn't exist, then you've achieved the desired outcome of the rm command, so therefore Success! Whereas without the -f option, you are explicitly asking rm to remove something and if it doesn't exist let me know!
BTW. There might be an error in your posted code.
You assign a "bad" directory to the variable dir dir=testdir1. But you cd $dir1, this is equivalent to cd with no parameters (because the variable dir1 does not exist). Therefore, it will cd back to your home directory (return value: success). Running rm -rf * from there might not be the best idea.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With