Consider the following:
root@debian-lap:/tmp echo "Step 1 " || echo "Failed to execute step 1" ; echo "Step 2"
Step 1
Step 2
root@debian-lap:/tmp
As you can see, the 1st and 3rd echo
command executed normally.
And if I the first command failed I want to stop the script and exit
from it:
root@debian-lap:/home/fugitive echo "Step 1 " || echo "Failed to execute step 1" && exit 2 ; echo "Step 2"
Step 1
exit
fugitive@debian-lap:~$
The exit
command executes and exits the shell, even thou exit code of the first command is 0. My question is - why?
In translation, doesn't this say:
- echo "Step 1"
- if the command failed , echo 'Failed to execute step 1' and exit the script
- else echo "Step 2"
Looking at this like :
cmd foo1 || cmd foo2 && exit
Shouldn't cmd foo2 and (&&) exit
execute only when cmd foo1
failed?
What I am missing?
Edit
I am adding 2nd example, something that I am really trying to do (still dummy test)
root@debian-lap:/tmp/bashtest a="$(ls)" || echo "Failed" ; echo $a
test_file # < - This is OK
root@debian-lap:
root@debian-lap:/tmp/bashtest a="$(ls)" || echo "Unable to assign the variable" && exit 2; echo $a
exit
fugitive@debian-lap:~$ # <- this is confusing part
root@debian-lap:/tmp/bashtest a="$(ls /tmpppp/notexist)" || echo "Unable to assign the variable" ; echo $a
ls: cannot access /tmpppp/notexist: No such file or directory
Unable to assign the variable # <- This is also OK
root@debian-lap:
\$
to the end of your$PS1
value.#
makes rest of the line commented out.