Search code examples
bashrootexitlogout

Exit causes root logout if script user executes the script outside of the script directory


Bash Script Bug User Gets Logged Out Of Root On Exit

I have a big Bash script which requires to exit the script and restart it if some user input is invalid. I got a weird bug, where if the user does execute the script outside of the directory in which the script is located, he gets logged out of root. But if the script is executed inside the directory where the script is located, this doesn't occur.

I already tried removing the exit but that only makes things worse.

#!/bin/bash

some_function() {

      read -p "Enter something: "

      # Some commands

      if [[ $? -gt 0 ]]; then
            echo "error"
            . /whatever/location/script.sh && exit 1
      fi

}

The expected result is, that the script just restarts and exits the process the user ran. The actual result is just like that, but the user gets logged out of root if the script is terminated after that.


Solution

  • You did not say so, but it seems you are sourcing the script containing this function that exits. If you are sourcing it, then it is as if each command is typed at the command line... so exit will logout of whatever shell you are running.

    For a script that is always sourced, use return instead of exit

    If you don't know whether the script will be sourced or not, you'll need to detect it and choose the proper behavior based on how it was called. For example:

    some_function() {
      read -p "Enter something: "
      # Some commands
      if [[ $? -gt 0 ]]; then
          echo "error"
          if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then
            # sourced
            . /whatever/location/script.sh && return 1
          else
            # not sourced
            . /whatever/location/script.sh && exit 1
          fi
      fi
    }