How Do You Keep a User from Logging off Unexpectedly?

Problem scenario
You have a Bash script that keeps logging out the user unexpectedly.  You have done research and nothing seems to work.  Your script does not use the reboot command.  Your script does use the exit command.

What do you do to keep the user from logging off while still using this script with the exit command?

This solution below is for one specific root cause.  There are different scenarios where you can have a user being logged out unexpectedly.  For general troubleshooting, you may want to see AskUbuntu or StackOverflow.  But if you have a script that has the exit builtin shell command, this solution may help you.

Are you running the script with the source command?  See if you can run the script with the bash command instead of the source command.

Are you running the script like this (with no quotes)?


Try this method instead (with no quotes to have the script run in a newly-forked shell):


If you must start the script using source (with the source command or this "." method), you may need to re-write the script.  The "exit" command when executed via a "sourced" bash script will exit as if the user entered the exit command.  When the script is executed with the bash command, the process is forked into a new shell.  If the script shares a shell, the exit command will terminate the shell of the user.

To demonstrate, create this two-line file in /tmp/:

cd /var

Now run change directories to /tmp/.  Run it like this:

bash; pwd

Now run it with source:

source; pwd

# With the "source" method, the working directory you will be in will be /var/.

Leave a comment

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