Juan.
Juan.

Reputation: 782

Stop "dd" inside a while loop after seconds

I cant figure out how to do it, what i need is after "c" seconds, dd stops. But it keeps working and ignore both the while loops and the seconds The script

read c
end=$((SECONDS+$c))

while [ $SECONDS -lt $end ]; do
    echo "Moving..."
    dd if=/dev/zero of=/dev/null 

done

Upvotes: 0

Views: 1426

Answers (2)

William Pursell
William Pursell

Reputation: 212228

That's not how loops work. Your construction will run until dd completes. If you want to terminate it after c seconds, you should either invoke it with timeout (almost certainly the preferred solution), or send it a signal explicitly. eg, something like:

dd if=/dev/zero of=/dev/null &
sleep $c
kill $!

Using & as the command terminator causes dd to be run asynchronously (aka "in the background"), so control returns immediately to the shell, storing the pid of the dd command in the variable $!. The shell then sleeps for a bit and sends a signal to terminate dd.

Upvotes: 2

Benjamin W.
Benjamin W.

Reputation: 52112

Adding my comment as an answer for completeness:

To stop a process after a given amount of time, you can run it using timeout if your system provides it; it is part of the GNU coreutils (but apparently not specified by POSIX).

In your case, instead of your loop, you could run

timeout "$c" dd if=/dev/zero of/dev/null

Upvotes: 3

Related Questions