I want to exit the current terminal and execute a command. Is it possible to do?

PS:: Assume that I have made a loop while true; do bash;done


You could execute it in a subshell with an appropriate trap. For example, if you wanted to execute echo -e '\nCommand done at the end of a while true; do true; done, you could use this:

mario@mario-K53SV:~$ (trap 'echo -e "\nCommand done"' EXIT; while true; do true; done)

The trap registers the command you defined on the EXIT event of the subshell. The parentheses are needed to make a subshell. Be aware that in case you want to generalize this, and put your commands in variables (e.g. MY_COMMAND='while true; do true; done'), you will need eval to execute them correctly. This example output shows exactly where it is useful (without eval, this wouldn't work):

mario@mario-K53SV:~$ YOUR_COMMAND="while true; do true; done"
mario@mario-K53SV:~$ EXECUTE_ON_EXIT="echo -e '\nCommand done'"
mario@mario-K53SV:~$ (trap 'eval ${EXECUTE_ON_EXIT}' EXIT; eval ${YOUR_COMMAND})
Command done


Should you wish so, this can also be used to automatically close your terminal too, at the end of the EXIT handler command: just include kill -s SIGHUP $$ at the end of your handler (e.g. EXECUTE_ON_EXIT="echo -e '\nCommand done'; kill -s SIGHUP $$").

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.