filpa
filpa

Reputation: 3634

Bash script to auto-kill a process after set amount of time, but also handle user interrupt

I have a very simple Bash script that runs top in batch mode for x seconds, saves the output to a file, and auto-kills top after a set amount of time

#!/bin/bash
# Runs top under batch mode with renewal period set to $1, saves the data to file $2,  and kills the process after $3 minutes

top -b -d $1 > $2 &

PROC=$!

(sleep $3m; kill $PROC) &

The thing is, I also want to be able to handle the killing of the script process, with something like this (I would prefer this over kill )

ctrl_c()
    # run if user hits control-c
    {
      echo -en "\n*** Done ***\n"
      cleanup # some cleanup function
      kill $PROC
    }

# trap keyboard interrupt (control-c)
trap ctrl_c SIGINT

while true; do read x; sleep $1; done

Is there a neater way of doing this?

Upvotes: 0

Views: 1341

Answers (1)

twalberg
twalberg

Reputation: 62379

Why not just give top a number of iterations to run for:

(( total_runtime = $3 * 60 ))
(( iterations = total_runtime / $1 ))
top -b -d $1 -n ${iterations}

Upvotes: 1

Related Questions