4

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:

run.sh:

#!/bin/bash 

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 ]
then 
     save_information_to_file()
fi;

Executed :

user: ./run.sh
2016-08-12 14:55:13 new bash subshell started...
SubShell: echo "wow..."
wow... 
SubShell: pwd
/home/username
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
exit
2016-08-12 14:59:41 new bash subshell ended !
user:

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

3

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 Aug 12 '16 at 20:09
4

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

#!/bin/bash 

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 Aug 12 '16 at 13:33
3

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 Aug 12 '16 at 18:58
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.