1

How can I throw error from nested shell script and make parent shell script to stop as well?

I have this shell script (a.sh)

#!/bin/bash
echo "Testing if SDK build config is correct"

FILE="App/env/index.tsx"
CONST_TO_CHECK='[a-zA-Z_]*'
RED=`tput setaf 1`
green=`tput setaf 2`
reset=`tput sgr0`

if grep -Eq 'export\s*const\s*'${CONST_TO_CHECK}'\s*=\s*false' "$FILE"; then
  echo "${RED}Error: All values should be true for sdk build in env.ts file${reset}"
  exit 1
fi

echo "${green}Build config seems correct${reset}"

Which I run from b.sh. If a.sh throws error, I want to stop further execution in b.sh as well.

I am calling b.sh from a.sh.

Consider this to be my b.sh

#!/bin/bash
sh ./a.sh

rm -rf ios/ios-sdk/out/Frameworks
xcodebuild clean \
    -workspace ios/dyteClientMobile.xcworkspace \
    -scheme DyteSdk

More code

1 Answer 1

2

Add -e to your #!. (This is also called "errexit" in the options.)

#!/bin/bash -e

In this mode, any command's failure (returning a non-0 value) will terminate the script. In order to ignore non-0 return values, add || true to commands, for example:

./a.sh || true

This would execute a.sh and continue whether it succeeds or not. Avoid prefixing sh here. Just execute the script directly.

For more examples of error handling Bash, and more advanced tools like ERR traps, see:

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for answering. So in my b.sh I replaced it with #!/bin/bash -e but it still continues to execute .
Copying your code and just adding -e in b.sh works fine for me. Any time it prints "Error: All values should be true for sdk build in env.ts file" it also stops executing. Is this your actual code? Are you running b.sh as ./b.sh or are you running it as sh ./b.sh (in which case you're disabling -e). If you want to run this by calling sh or bash directly, you can use set -o errexit in the script rather than -e. That sets the value directly without relying on the shbang execution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.