Mark Roy
Mark Roy

Reputation: 31

Delay for every command execution in shell script

I'm a newbie here so please forgive my ignorance. I just want to ask if there is a way to put a delay for each commands execution in a shell script.

This is my current setup

command1
sleep 1
command2
sleep 1
.....
.....
command1000
sleep 1

Is there a way to put just 1 sleep command ( delay 1 second) after execution of each command. Thank you in advance!

Br, Mark

Upvotes: 2

Views: 2126

Answers (2)

Shiva
Shiva

Reputation: 2838

Script:

declare -a cmd_list=("echo how" "echo are" "echo you")

for cmd in "${cmd_list[@]}"
do
  eval "$cmd"
  sleep 1
done

You have to replace the echo <param> with your commands and args.

Explanation:
I am have declared an array of commands in strings(first line), then I loop through the array and evaluate(eval "$cmd") each string. After the command from the array, a sleep command is executed.

Upvotes: 0

that other guy
that other guy

Reputation: 123470

In Bash (but not other shells) you can do this with a debug trap:

#!/bin/bash
trap 'sleep 1' DEBUG
for word in The GNU General Public License is a free, copyleft license
do
  printf '%s ' "$word"
done

Here's help trap:

trap: trap [-lp] [[arg] signal_spec ...]

Trap signals and other events.

If a SIGNAL_SPEC is DEBUG, ARG is executed before every simple command.

Upvotes: 2

Related Questions