Exit from Bash script on error without closing the terminal window

To terminate the script in case of an error, we can use the “-e” option.

set -e


#!/bin/bash -e

When a bash script is

  • “sourced”,
  • called from an alias with a leading dot like my-alias='. /my-script to execute in the same process, or
  • a function is executed from a terminal window

and the script exits on an error, it closes the terminal window.

To keep the terminal open, execute the script in a subprocess. It is easy to update existing scripts. Enclose the main part of the script in parentheses to open a new subprocess and add the “set -e” option to it. In case of an error the script terminates the subprocess and returns to the terminal session.


my_function() {

  set -e
  my entry point to the script

Leave a comment

Your email address will not be published. Required fields are marked *