MAK MAK - 5 months ago 29
Bash Question

Unix Shell Script: While loop

I want to print the numbers in the following pattern using WHILE loop.

0
01
012
0123
.....
......
0123456789


My Try:



#!/bin/sh

a=0
b=0

while [ $a -le 10 ]
do
while [ $b -le $a ]
do
echo -n "$b"
b=`expr $b + 1`
done
echo
a=`expr $a + 1`
done


Getting output:

0
1
2
3
4
5
6
7
8
9
10

Answer

As you simply append the latest count to the line output, simply do so as text.

#!/bin/bash

a=0
out=''

while [ $a -lt 10 ]
do
    out=$out$a
    echo $out
    a=`expr $a + 1`
done

Also, le is less or equal, so you end up with 10. Use lt 10 or le 9.