1

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?

Vladimir
  • 157
  • 2
  • 16
  • 1
    That first one should work the way you want if the script fails. The second one appears wrong on the third line. The way it is being used, it looks like that line should be `sh -c "$url"`. Looks like if curl fails, it may return a good return code. See [this](https://stackoverflow.com/a/18262020/635822) answer. – Jason Jun 17 '20 at 14:22
  • Ideally, you'll fail before `sh` runs at all. It would be best to verify that the full output of `curl` is the script you expect before executing `sh`. Save the script to a file, verify it, *then* just run `sh theScript.sh`. – chepner Jun 17 '20 at 16:18

1 Answers1

2

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.

oguz ismail
  • 1
  • 16
  • 47
  • 69
  • 2
    Nice answer. I try to avoid `set -e` in general. For something like this, I would prefer to check the return code with `if sh -c ...` or just make it a one-liner. `sh -c "$(curl -f "${SCRIPT_URL}" || echo exit 1)" && echo succeed` – Jason Jun 17 '20 at 14:41