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?
Best Answer
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!