1

I am copying a file using dd command:

dd if=in.dat of=out.dat bs=1kb

Suppose the input file is very big and the complete copy will take say 5 min to complete. I want to break dd command after 1 min.

How to achieve this in shell script?

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
Naveen
  • 91
  • 1
  • 7
  • You're quite content to just copy 20% of the data and stop there? – sarnold Jan 16 '12 at 07:08
  • While I've been surprised by the amount of things `bash(1)` can do, I have trouble seeing an "easy" way to do this wish `bash(1)`. Another tool such as Ruby, Python, Perl, C, would probably be easier. – sarnold Jan 16 '12 at 07:13
  • BTW, I guess `op=` is a typo. It must be `of=`. – jman Jan 16 '12 at 07:16
  • possible duplicate of [script to time limit process on posix](http://stackoverflow.com/questions/4355396/script-to-time-limit-process-on-posix) – Jonathan Leffler Jan 16 '12 at 07:19

2 Answers2

3

Try this:

dd if=a.dat of=b.dat bs=1kb &
p=$!
sleep 60
kill -9 $p
jman
  • 11,334
  • 5
  • 39
  • 61
  • Any ideas how to run more quickly if the `dd` finishes in ten seconds? – sarnold Jan 16 '12 at 07:14
  • Oh you could sleep for fewer seconds (in a loop that adds up to 60s) and check if process with PID `$p` is still running. – jman Jan 16 '12 at 07:16
  • Thanks. So the '&' in the end makes dd to execute as if it is a different background process ? so our script will sleep for 60sec but dd will be executing in the background. Thanks thats exactly what i am looking for. – Naveen Jan 16 '12 at 07:18
  • 1
    Using `kill -9` is a very violent way of killing processes. Use plain `kill`; it sends a SIGTERM signal which is much more appropriate. – Jonathan Leffler Jan 16 '12 at 07:22
  • Care to elaborate? SIGTERM can be ignored but SIGKILL can't be. What do you mean by violent? There is absolutely nothing wrong in using SIGKILL if that is your intention. – jman Jan 16 '12 at 07:25
  • @skjaidev SIGKILL doesn't allow the process to terminate gracefully. It's akin to cutting the phone line instead of telling the party on the other end that you're going to hang up now. – SiegeX Jan 16 '12 at 22:22
  • That part is obvious. Why is SIGKILL bad _in this case_? Its not like dd creates temp files. – jman Jan 17 '12 at 00:23
  • @skjaidev I like to think of it like a cop, use only as much force as necessary. It's also not like `dd` ignores SIGTERM – SiegeX Jan 17 '12 at 05:44
2

Kill the most recently backgrounded process via $! after 60 seconds

dd if=a.dat of=b.dat bs=1kb &
sleep 60 && kill $!
SiegeX
  • 135,741
  • 24
  • 144
  • 154