Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I coded a progress indicator in the form of a falling deck of cards (my wife's idea).

It's not in its final form yet. Here is the code:

vdeck="| | | | | "
hdeck[1]="__ | | | |"
hdeck[2]="__ __ | | |"
hdeck[3]="__ __ __ | |"
hdeck[4]="__ __ __ __ |"
hdeck[5]="__ __ __ __ __"

while true
do
    clear
    echo -n -e "\r$vdeck"
    sleep 0.8

    for i in 1 2 3 4 5
    do
        echo -n -e "\r${hdeck[$i]}"
        sleep 0.2
    done
    clear
done

Is it possible to optimize this code without having a hdeck array and getting the same effect? Increasing '|' means increasing the 'hdeck' array combinations, which isn't good.

share|improve this question
up vote 3 down vote accepted

Something like this?

#!/bin/bash
LEN=5
echo 'start';
for (( i=0; i<((${LEN}+1)); i++ )); do
echo -ne '\r' 
        for (( j=0; j<${i}; j++ )); do
                 echo -n '_'
        done
        for (( j=${i}; j<${LEN}; j++ )); do
                 echo -n '|'
        done
sleep 0.5
done
echo -e '\ndone'
share|improve this answer
    
As an aside, aren't you supposed to be able to use variables in the shorter "for i in {1..10}" syntax? I couldn't get "for i in {1..${LEN}}" to work which would've shortened the code somewhat. – Tzarium May 11 '11 at 8:57

Well, why don't you have a single string (all '|') and try replacing the (first) '|' with '-' in every iteration of the loop?

Example of string replacement:

stringZ=abcABC123ABCabc

echo ${stringZ/abc/xyz}       # xyzABC123ABCabc
                              # Replaces first match of 'abc' with 'xyz'.

That way, you don't need multiple strings without the hdeck array.

Try this:

deck="| | | | | "

while true
do
    clear
    echo -n -e "\r$deck"
    sleep 0.8

    for ((i=1; i<=`expr length $deck`; i++))
    do
        echo -n -e "\r${deck/|/-}"
        sleep 0.2
    done
    clear
done

The above script should do it.. This is just an indicative script and I have not run it myself.. Please check for syntax errors..

More information on string manipulation in bash is here - http://tldp.org/LDP/abs/html/string-manipulation.html

share|improve this answer
    
Tzarium's code above is more elegant than mine – Vinay May 11 '11 at 9:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .