latestVersion
latestVersion

Reputation: 458

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.

Upvotes: 7

Views: 8947

Answers (4)

Leif Neland
Leif Neland

Reputation: 1508

This should work, even if OP didn't want to move the exit.

#!/bin/sh
ls -l ~/.
RES=$?     #save res for later.
touch ~/abc.txt
exit $RES

Upvotes: 0

William Pursell
William Pursell

Reputation: 212268

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.

Upvotes: 10

Nykakin
Nykakin

Reputation: 8747

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.

Upvotes: 1

arkascha
arkascha

Reputation: 42925

I doubt the direct way is possible in any way.

But there might be a workaround: can you wrap the executing script in another process ? Then you could call anything you want in the wrapping script once the wrapped script executed its exit() and is removed from the stack.

Upvotes: 0

Related Questions