Click to See Complete Forum and Search --> : bash 1 liner


0x12d3
03-04-2003, 04:45 AM
does anyone know of a bash one liner to run a command and then kill it after some duration? For the example the job is dd if=/dev/zero of=/dev/null aliased to ddzn. I've tried many variations of the following:

for i in 5; do ddzn & sleep $i; exit; done

while [ ddzn ] ; do sleep 5; done

while [ $(ddzn) & ]; do sleep 5; done

ddzn & sleep 5; kill %1 <===this works from command line but not within a script unless run as source scriptname and even then it breaks when put in the background (ie source scriptname &) defining a function within the script also fails.

Tons of other craziness. It seems the command can't be called as the conditional as it needs an exit status before the loop begins. It can't be called within the while because if it is run in the background it doesn't exit when the script ends, and if it's called without the background operator (&) then it never exits for the next command to run. As for the last example it seems that the "%1" argument lacks sufficient scope. I'm looking for a nearly shell only implementation (std sys progs are ok...ie sleep, kill, etc). Any info on bash "exporting" or otherwise handling of pid's will be greatly appreciated. Any suggestions?

bwkaz
03-04-2003, 02:57 PM
(ddzn &) ; sleep 5 ; killall dd

perhaps? I don't know if it works in a script, but it might.

It starts up ddzn in the background, in a subshell. Then it sleeps for 5 seconds and kills all processes whose names (according to ps ax) are "dd". This should take care of the ddzn thing -- if not, try changing killall dd to killall ddzn.

0x12d3
03-05-2003, 08:13 AM
thnx. I've considered the killall earlier, but however the job is started it will always run as "dd" and could potentially interfere with other jobs (I also couldn't run multiple instances).

Strike
03-05-2003, 12:54 PM
Store the PID in a temp file (echo $PID > /tmp/ddzn.pid), then kill the specific PID when it's done (kill `cat /tmp/ddzn.pid`)

Can't run the script multiple times at once, but that may or may not matter for the particular script.

chrism01
03-05-2003, 02:29 PM
Try this: $! is the pid of the last bacground cmd, so save this immediately after starting it in the background

eg

prog &
saved_pid=$!

0x12d3
03-05-2003, 07:53 PM
Thanks for the input. The "$!" variable is _exactly_ what I was looking for. Everything works perfectly. Thnx again all. I appreciate it chrism01.