简体   繁体   中英

Executing multiple Bash commands after OR

I'm writing a Bash script to install some software; Is there a way to create a one liner that executes multiple commands after an OR? Basically, what I want to do for error checking is is this:

sudo apt-get install fortune || (echo "Installation failed" ; exit)
echo "Installation successful"

I've tried this, but it doesn't exit the script when the installation fails, and still outputs "Installation successful" as well. Any ideas on how to edit this method to make it work?

Parentheses create a subshell, which is what the exit commands exits. You want a command group , defined with braces.

sudo apt-get install fortune || { echo "Installation failed" >&2; exit 1; }

(Note the last semicolon and the spaces around the braces; all are important.)

To keep things more readable, typically you define a function to act as the single command following || :

abort () { echo "Installation of $1 failed" >&2; exit 1; }

sudo apt-get install fortune || abort fortune

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM