echo hello; echo hi
is identical to this in a script:
echo hello
echo hi
How do I do the same to the following possibilities?
echo hello && echo hi
echo hello || echo hi
I presume I can do this:
echo hello && \
echo hi
echo hello || \
echo hi
But this is more or less imitating a multi-line script
What is the appropriate way of doing this?
edit: I am aware of how && and || work, I am just wondering how to effectively replicate it in a multi-line script
You can use if
:
if echo hello; then
echo hi
fi
if ! echo hello; then
echo hi
fi
echo one && echo two
prints one, and if that returns 0 it prints two, too.
echo one || echo two
prints one, and if that doesn't return 0 prints two, too.
You can use it to shorten if
statements, like so:
if [[ 1 -eq 2 ]]; then doStuff; fi
shortens to
[[ 1 -eq 2 ]] && doStuff
Another example would be my startx
script I run to update, then startx on my Ubuntu machine
sudo apt-get update && sudo apt-get -y upgrade && apt-get -y autoremove && startx
What that does is chain &&
together (remember all &&
does is check if the command "piped" to it exits with 0) in a way that only the next command is run if the last is run without errors. I do this so that if for some reason apt
fails me, I can fix it from my terminal without waiting for xorg to do it's thing.
EDIT:
If you want to "expand" &&, to more lines use:
commandToCheckReturnOf
if [[ $? -eq 0 ]]; then
doStuff
fi
If you're after ||
, then:
commandToCheckReturnOf
if [[ $? -ne 0 ]]; then
doStuff
fi
Sorry for the misunderstanding.
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