LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   Q: count inside a loop (http://www.linuxquestions.org/questions/linux-general-1/q-count-inside-a-loop-4175452325/)

Dr_Death_UAE 03-01-2013 07:30 PM

Q: count inside a loop
 
hello

i am trying to write a for-loop that doesn't start from 1, but the loop count start from 1

Code:

for (( i=$a; i <= $b; i++ )); do echo "$x:$i"; done
where $a and $b always have different value
i want the result be like this:
Quote:

1: 10
2: 11
3: 12
4: 13
5: 14
6: 15
7: 16
8: 17
9: 18
10: 19
11: 20
any idea, thanks

kooru 03-02-2013 03:24 AM

If I understand well..

Code:

#!/bin/bash

x=1
a=10
b=20

for i in `seq $a $b`
do
echo "$x: $i"
x=$((x+1))
done


H_TeXMeX_H 03-02-2013 05:04 AM

Or even simpler:

Code:

bash-4.2$ for i in $(seq 1 11); do printf '%d: %d\n' "$i" "$(($i + 9))"; done
1: 10
2: 11
3: 12
4: 13
5: 14
6: 15
7: 16
8: 17
9: 18
10: 19
11: 20


Dr_Death_UAE 03-02-2013 07:04 AM

thanks kooru,
Quote:

x=$((x+1))
did the trick :)

chrism01 03-04-2013 12:15 AM

This is a simple way
Code:

for (( x=1,i=10 ; x <= 10, i<=20; x++, i++))
do
    echo "$x:$i"
done

# ./t.sh
1:10
2:11
3:12
4:13
5:14
6:15
7:16
8:17
9:18
10:19
11:20

:)

Dr_Death_UAE 03-04-2013 12:20 AM

Quote:

Originally Posted by chrism01 (Post 4904073)
This is a simple way
Code:

for (( x=1,i=10 ; x <= 10, i<=20; x++, i++))
do
    echo "$x:$i"
done

# ./t.sh
1:10
2:11
3:12
4:13
5:14
6:15
7:16
8:17
9:18
10:19
11:20

:)

thanks chrism01, i never thought it's possible to do it in this way

thanks again :hattip:

chrism01 03-04-2013 12:24 AM

No worries; glad to help :)


All times are GMT -5. The time now is 11:30 AM.