3

What I'm doing is,

trap 'rm -f /path/of/file/fileName.running; echo "TRAPPED & READY";' 1 2 9 15 >> trap.log 

I didn't get anything in log & the file which should have been deleted still exists, I'm not sure of which signal could be stopping the script while it's running as I'm just killing the servers which are being used by the script.

NB: My Cron-Scheduled job won't run if that file is present & I don't think I've missed any possible signal. where am I wrong?

1
  • Note that you can't trap SIGKILL (9), that's the whole point of that signal (kill unconditionaly). Commented Aug 12, 2014 at 9:31

2 Answers 2

3

Part of your problem is that you have the >> trap.log outside the (quoted) command arg, so all you’re getting in the trap.log file is the output from the trap command itself – which is nothing. I’m not sure what you mean by saying “TRAPPED & READY” when your script is terminating, but it looks like what you mean is

 trap 'rm -f filename; echo "message" >> trap.log' sigspec

And I agree with Karlo: if you are “just killing the servers which are being used by the script,” then the script is quite probably exiting (rather than being killed by a signal) and you should use the EXIT (or, equivalently, 0) sigspec (possibly in addition to 1, 2, and 15).

P.S. You don’t need a semicolon (;) at the end of the trap command arg.

1
  • That was short for, 'Trapped the signal and is ready for the next run' Thanks :) I didn't get that below exit usage though. Commented Aug 14, 2014 at 8:04
2

Use EXIT instead of the signal numbers.

The script below works for me. I use the constants.

> cat test.sh #!/bin/bash trap 'echo trap' EXIT echo 'Program running' sleep 1 > ./test.sh Program running trap 

From the bash manpage:

If a sigspec is EXIT (0) the command arg is executed on exit from the shell. If a sigspec is DEBUG, the command arg is executed before every simple command, for command, case command, select command, every arithmetic for command, and before the first command executes in a shell function (see SHELL GRAMMAR above). Refer to the description of the extdebug option to the shopt builtin for details of its effect on the DEBUG trap. If a sigspec is RETURN, the command arg is executed each time a shell function or a script executed with the . or source builtins finishes executing.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.