How to save an exit code to a variable in bash script

Published on February 08, 2021

I had to save the exit code from one part of the script that runs a suite of tests, then run some cleanup and finally return the exit code received previously from the tests.

I haven’t used bash scripts too often in my work so when I had to do this recently I had to spend some time looking up syntax.

This will fail the tests correctly in our Azure Devops pipeline while still cleaning up the docker containers.

The script

The part I found difficult here was the escaping. Sometimes you need double quotes and other times it’s just the variable. This is a reference in case I ever have to do this again!

Note that to run this you will have to give it permissions chmod 755 myscript.sh

#!/bin/bash

main (){
   docker-compose run node
   exitCode=$?

   echo "exitCode will be $exitCode"
}

setup(){
   yarn
   docker-compose up -d chromedriver
   docker ps -a
}

tearDown(){
    docker-compose down
    docker system prune -f
}

setup
main
tearDown

exit "$exitCode"
Darragh ORiordan

Hi! I'm Darragh ORiordan.

I live and work in Sydney, Australia enjoying the mountains and the ocean.

I build and support happy teams that create high quality software for the web.

Contact me on Twitter!


Sign up for the newsletter

Get new writings, curated tech articles and coding tips!

Read the Privacy Policy.