简体   繁体   中英

Stop bash on error same as “set -e” in script file

I have an external command to produce some bash commands, let's call it gen_commands , it produces a list of commands that I need to run with bash , but if any command fails I need to stop and exit. To stop it on error I'm writting the result of gen_commands to temporary script file appending set -e at the beggining:

echo "#!/bin/bash" > tmp.sh
echo "set -e" >> tmp.sh
gen_commands >> tmp.sh
chmod +x tmp.sh
./tmp.sh
rm tmp.sh

It would look much cleaner if I can run it with one line:

gen_commands | bash

but in that case bash ignores errors. Is it possible to configure bash to fail on error without writting to sccript file.

You can use a command group to combine the output of multiple commands into one stream:

{ echo "set -e"; gen_commands; } | bash

However, you can simply pass -e as an option to bash as well:

gen_commands | bash -e

From the man page:

OPTIONS

All of the single-character shell options documented in the description of the set builtin command can be used as options when the shell is invoked.

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