Kirill
Kirill

Reputation: 8341

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.

Upvotes: 0

Views: 87

Answers (1)

chepner
chepner

Reputation: 532313

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.

Upvotes: 1

Related Questions