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

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

I want to find a solution for something like

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

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

Limitations: 1) Can't I change the exit $? part exit $? the above script. 2) The command should be executed only after the exit $? .

I am not sure if there is a solution for this, but any help is appreciated.

+6
source share
4 answers

A typical approach is to set a trap:

 trap 'touch ~/abc.txt' 0 

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

+10
source

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

+1
source

I doubt that a direct path is possible in any case.

But there may be a workaround: can you wrap script execution in another process? Then you can call whatever you want in the script wrapper as soon as the wrapped script executes its exit () and is removed from the stack.

0
source

This should work even if the OP does not want to move the output.

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

Source: https://habr.com/ru/post/921484/


All Articles