MAK
MAK

Reputation: 7270

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

Upvotes: 1

Views: 6792

Answers (3)

Alex
Alex

Reputation: 1

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

echo                                                                                                                                                             

b=`expr $b + 1`                                                                                                                                                  

done  

Upvotes: 0

Jdamian
Jdamian

Reputation: 3125

If you use bashshell, you can take advantage of sequence expressions of the form {x..y} and use the special parameter $_ which usually expands to the last argument to the previous command.

#/bin/bash
i=
for i in {0..9}
do
     echo "$_$i"
done

Upvotes: 1

Ben CT
Ben CT

Reputation: 54

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.

Upvotes: 4

Related Questions