Vladimir
Vladimir

Reputation: 157

Force sh to fail if the command substituting its command string fails

I want to exec bash script from URL.
I use sh -c "$(curl -f ${SCRIPT_URL})".
It is worked, but parent script complete successfully if url is incorrect or child script give error.

Example:

set -e
sh -c "$(curl -f ${SCRIPT_URL})"
echo "success"

I can get a need error with using an additional variable:

set -e
url=$(curl -f ${SCRIPT_URL})    
sh -c "$url"
echo "success"

But I don't want to use an additional variable. Is it possible to do it without additional variable?

Upvotes: 1

Views: 476

Answers (1)

oguz ismail
oguz ismail

Reputation: 50775

Write exit 1 if curl fails, so that sh will exit with a status of 1, and set -e will take effect.

set -e
sh -c "$(curl -f "${SCRIPT_URL}" || echo exit 1)"
echo success

Using a variable or an intermediate file, and handling errors without relying on set -e is indeed a better approach though.

Upvotes: 2

Related Questions