1

I have following command i use in a script as a countdown timer and it works great

#  30 sec Countdown Timer
for i in {30..1};do echo -n "$i." && sleep 1; done

Output:30.29.28.27.26 etc....

But I would like to be able to output in 5sec intervals like

: 30.25.20.15 etc..

how can i change the script to do this ?

tubos
  • 69
  • 2
  • 9

3 Answers3

10
for i in {30..1..5};do echo -n "$i." && sleep 5; done
Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • 1
    I would have upvoted it immediately but it took me 30 seconds to test your code :) – Tom Fenech Sep 27 '14 at 10:14
  • 3
    @Tom Fenech: :) This reminds me of this: How do I calculate the date of tomorrow? `sleep $((60*60*24)); date` – Cyrus Sep 27 '14 at 10:19
  • 2
    :) And that reminded me of [sleepsort](http://stackoverflow.com/questions/6474318/what-is-the-time-complexity-of-the-sleep-sort). – PM 2Ring Sep 27 '14 at 17:50
  • 1
    Note that this approach requires `bash` 4.0 or newer. Could alternatively do `seq 30 -5 1`. – John B Sep 27 '14 at 19:22
  • @PM2Ring: \*lol\* very nice. @JohnB: thank you for the hint. Alternatively do: `for ((i=30;i>0;i=i-5)); do echo -n "$i." && sleep 5; done` – Cyrus Sep 27 '14 at 19:34
2
for i in {30..1}
do 
  if [ $((i%5)) == 0 ]
  then 
    echo -n "$i."
  fi
  sleep 1
done
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86
  • Just a suggestion: your condition could be `if ((i%5 == 0))` – Tom Fenech Sep 27 '14 at 12:23
  • 1
    Of course, although it seems redundant to use `[` and `$(( ))` together in bash. If you _are_ going to use `[`, you should change `==` to `=` (or better yet, `-eq`), as `==` is not understood by other POSIX shells. If you did that, your version would be more portable than my suggestion, which is bash-specific. – Tom Fenech Sep 27 '14 at 16:50
  • 1
    If you _need_ the portability, use `[`, but otherwise _please_ use `[[` and your life will be easier. :) See [Conditional Blocks](http://mywiki.wooledge.org/BashGuide/TestsAndConditionals?#Conditional_Blocks) and [Bash Tests](http://mywiki.wooledge.org/BashGuide/Practices?#Bash_Tests). – PM 2Ring Sep 27 '14 at 17:48
0

Here is straightforward script compatible with Dash and Bash:

i=30 && while [ $i -gt 0 ]; do sleep 5; i=$(($i-5)); printf "$i."; done
Onlyjob
  • 5,692
  • 2
  • 35
  • 35