Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using && and || in multiline bash script [closed]

Tags:

bash

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

like image 301
Miati Avatar asked Dec 20 '14 23:12

Miati


2 Answers

You can use if:

if echo hello; then
    echo hi
fi

if ! echo hello; then
    echo hi
fi
like image 76
Ry- Avatar answered Sep 30 '22 23:09

Ry-


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.

like image 45
MeetTitan Avatar answered Oct 01 '22 00:10

MeetTitan