I want to execute bash in subshell and when user exits from subshell, I want to execute some other commands (like for saving logs to file).

Something like this:



function save_information_to_file()
    echo "${date} ${time} new bash subshell ended !"
# Some commands etc.

env PS1='SubShell:' bash --rcfile /home/username/.bashrc

if [ user_logout_from_subshell ]

Executed :

user: ./run.sh
2016-08-12 14:55:13 new bash subshell started...
SubShell: echo "wow..."
SubShell: pwd
SubShell: cat user.log
2016-08-11 17:54:32 bash started
2016-08-11 17:56:14 bash ended
2016-08-11 18:23:18 bash started
2016-08-11 18:39:30 bash ended
SubShell: exit
2016-08-12 14:59:41 new bash subshell ended !

How to run bash with path to file that have to be executed on exit?

4 Answers 4


You don't need any special tricks. This is enough:


env PS1='SubShell:' bash --rcfile /home/username/.bashrc

echo Subshell exited. Now doing something...

The subshell will run in the main terminal. The main script will wait for it to finish without any extra commands.

(I don't know how you can set PS1 from above the shell. I guess it gets overwritten at the subshell Bash startup.)

  • My mistake - PS1 is set in rcfile :)
    – TMSeth
    Commented Aug 12, 2016 at 13:33

My first thought was .bash_logout too, but that only works for login shells. The most straightforward method, which works for both login and non-login shells, is setting a trap on exit. It works like this:

trap "your_commands_go_here" EXIT

For example, $ bash $ trap "echo goodbye cruel world!" EXIT $ exit exit goodbye cruel world!

  • BTW, this was the question that finally made me join U&L!
    – stangdon
    Commented Aug 12, 2016 at 20:09

There is a file in home directory of each user named .bash_logout, try to insert the commands you want in it.

  • 1
    .bash_logout only executes when a login shell exits. He's not creating a login shell.
    – Barmar
    Commented Aug 12, 2016 at 18:58

There is the possibility that .bash_logout does not already exist in your home directory. I've run into this in the past. If this is the case, just vi/vim and create your own .bash_logout file in your home directory and this should do the trick.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .