Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script: Execute command after running "exit" command in the shell script

I have a situation where in I have a command in my shell script that must be executed after a exit command is executed in the same script (I know!! It sounds crazy!!)

I want to find a solution for something like

#!/bin/sh
ls -l ~/.
exit $?
touch ~/abc.txt

Here I want the command touch ~/abc.txt execute after exit $? has run and the command touch ~/abc.txt can be any command.

Constraints: 1) I cannot modify the exit $? part of the above script. 2) The command must be executed only after the exit $? command.

I'm not sure if there is a solution for this but any help is appreciated.

like image 534
latestVersion Avatar asked Jul 27 '12 11:07

latestVersion


People also ask

How do you exit a shell script command?

To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.

How do I exit shell script without exiting shell?

Use return . The return bash builtin will exit the sourced script without stopping the calling (parent/sourcing) script. Causes a function to stop executing and return the value specified by n to its caller.


2 Answers

The typical approach is to set a trap:

trap 'touch ~/abc.txt' 0

This will invoke the touch command when the shell exits. In some shells (eg bash), the trap will also be executed if the script terminates as the result of a signal, but in others (eg dash) it will not. There is no portable way to invoke the command only if the last command was exit.

like image 141
William Pursell Avatar answered Oct 05 '22 19:10

William Pursell


I don't know why you want to do something like that but maybe try something like this: wrap your script in another one. In your parent script evaluate your child script with command like eval or source, then extract from your child script last command and execute it separately same way.

like image 23
Nykakin Avatar answered Oct 05 '22 20:10

Nykakin