2

I have written below script:

#!/bin/bash
sleep 15

function_signalr()
{
date
date | awk '{printf "%-15s\n", $2}' 
}

trap "function_signalr" 10

When I start the process by "process &" it runs, the PID is given. I do kill -10 PID, but my trap does not work. The process is killed, but the trap did not sprung. No date message is given. I will be grateful for any advice.

Jolta
  • 2,620
  • 1
  • 29
  • 42
user3214667
  • 57
  • 1
  • 1
  • 2

1 Answers1

5

Your trap doesn't work because the shell doesn't know about it yet.

You need to define the trap function, set the trap and then write your code.

#!/bin/bash

function_signalr()
{
date
date | awk '{printf "%-15s\n", $2}' 
}

trap "function_signalr" 10

# Code follows now
sleep 15

Moreover note that sleep is blocking which implies that if you do kill -10 PID then the trap wouldn't execute until sleep is done.

devnull
  • 118,548
  • 33
  • 236
  • 227
  • Thank you. I have changed the order of the script and now after sleeps completes the date is executed. Is it possible to terminate the sleep and execute the trap immediately or do I always have to wait for the previous command to complete? – user3214667 Apr 06 '14 at 14:12
  • @user3214667 I'm not sure what you're trying to achieve here. As mentioned above, `sleep` is blocking so `trap` won't be executed while you're sleeping. But you could put the `sleep` in a loop in order to execute the `trap` earlier: `for ((i=1;i<=15;i++)); do sleep 1; done` – devnull Apr 06 '14 at 16:29
  • I am just doing a bash course and some parts are tricky. Thank you for your help. – user3214667 Apr 07 '14 at 11:28