How to print a sequence of 100 numbers using shell script or bash shell while loop ?

Today lets see quickly how to print a sequence of 100 numbers using while loop in bash shell on Linux.

Printing sequence of 100 numbers

a. Empty the file.
[root@ngelinux001 ~]# echo > a.txt

b. echo each number in a file a.txt till 250.
To print till 100, we can change "257" with 101.

[root@ngelinux001 ~]# i=1; while [ $i -lt 257 ] ; do echo $i >> a.txt; (( i = $i + 1 )) ; done
[root@ngelinux001 ~]# wc -l a.txt
257 a.txt
[root@ngelinux001 ~]# tail a.txt
247
248
249
250
251
252
253
254
255
256

 

Understanding the command

[root@ngelinux001 ~]# i=1; while [ $i -lt 257 ] ; do echo $i >> a.txt; (( i = $i + 1 )) ; done

a. Set variable i initial value is 1.
b. Run a look till i is less than 257 i.e. till i=256
c. echo value of i into file “a.txt”
d. Increment the value of i by 1

Leave a Reply

Your email address will not be published.