2

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

3
  • What shell do you use? Commented Jul 21, 2018 at 20:26
  • sorry i didnt specity. I'm using a bash shell. Commented Jul 21, 2018 at 20:29
  • command1; sleep 1; command2; sleep 1 ? Commented Jul 21, 2018 at 20:36

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot!it works! i put trap 'sleep 1' DEBUG at the beginning of my script!I really appreciate your help!
Hi that_other_guy, i just have an extra question if you are not busy, in my script i put set -e in order to close the script if there is an error. I have a command that was executed fine but script still close. Although the command was executed without output (meaning no existing configuration in the equipment), I thought "set -e" will close the script only if the command is wrong or there is a syntax error.Any idea on this, or maybe my understanding is wrong. Thanks in advance!
set -e may (but is not guaranteed to) exit the script when the command itself reports failure. Some commands report failure even though they completed their job perfectly in order to signal a testable condition, like how grep "fails" if it can't find a match.
0

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.

1 Comment

Hi shiva! Thanks a lot for your help! Its very nice to include explanation! I havent tried your scipt but I'm sure it will work. I'm a newbie with scripting. I will study your script and will try in few hours. Thanks in advance again! I will let you know of the result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.