≡ Menu

Shell Scripting: Generate or Print Range of Numbers ( Sequence of Numbers for Loop )

One our reader asks:

How do I generate a range of numbers under BASH for loop command? For example, I need to run particular command inside loop 100 or 500 times. Basically I want function that counts FROM and TO a range of numbers like 50-10.

To print a sequence of numbers use GNU seq command. In olden days we use our own shell script. But no more dirty shell script, just use good seq command.

This is quite handy when you want to writing shell scripts that requires loop-using range of numbers.

seq command syntax

seq LAST
seq FIRST LAST
seq FIRST INCREMENT LAST

If FIRST or INCREMENT is omitted, it defaults to 1. That is, an omitted INCREMENT defaults to 1 even when LAST is smaller than FIRST. FIRST, INCREMENT, and LAST are interpreted as floating point values. INCREMENT is usually positive if FIRST is smaller than LAST, and INCREMENT is usually negative if FIRST is greater than LAST.

Try out following examples:
$ seq 5
Output:

1
2
3
4
5

Few more examples:$ seq 5 10
$ seq 0 2 10
$ seq 5 -1 1

seq command and shell script (for loop)

You can use seq command in bash for loop as follows:

#!/bin/bash
for i in $(seq 5)
do
  echo "Welcome $i times"
done
 

Bash for loop to generate a sequence of numbers

You can also use bash for loop as follows:

#!/bin/bash
for ((a=1; a <= 5 ; a++))
 do
    echo "Welcome $a times."
 done

Real World Experience

#!/bin/bash
# Script to move topics from old shared hosting to new lighttpd vps server
#
U="http://forum.cyberciti.biz/viewtopic.php?t="
rdu=""
for n in $(seq 1 521)
do
  rdu="$(lynx --dump $U$n | egrep "vt([0-9]+)\.html$" | awk '{ print $2}' | uniq)"
  if [ "$rdu" == "" ]; then
    :
  else
    echo "$n => \"$rdu\","
  fi
  rdu=""
done

Above script generates a new php code (array) to match with variable t so that we can send 301 redirect. So anyone visiting old forum url http://www.cyberciti.biz/nixcraft/forum/viewtopic.php?t=513 will be redirected to new url :D
Next, I just need to copy and paste the array generated by shell script into viewtopic.php and all users are redirected to new url with 301 http code.

<?php
 $URLS = array (
 ....
 ..
 3 => "http://forum.cyberciti.biz/mysql-cluster-vt3.html",
4 => "http://forum.cyberciti.biz/nice-look-and-feel-vt4.html",
5 => "http://forum.cyberciti.biz/squid-monitoring-using-mrtg-vt5.html"
....
);
$top=$_GET['t'];
$u=$URLS[$top];
if ( isset($u)) {
  @include_once("../../include.genlib.php");
  movePage(301, "$u");
}
else
{
  @include_once("../../include.genlib.php");
  movePage(301, "http://forum.cyberciti.biz");
}
?>

Set a step value and generate a sequence number

In case, you are interested in my old (perhaps dirty) shell script ;)

#!/bin/bash
# Usage:
# ./script 1 5 +
# ./script 100 50 -
# where    START END +/-
FROM=$1
TO=$2
ACTION="$3"
if [ "$ACTION" == "+" ];
then
while [ $FROM -le $TO ]
do
  echo -n $FROM " "
  (( FROM++ ))
done
echo ""
else
while [ $FROM -ge $TO ]
do
  echo -n $FROM " "
  (( FROM-- ))
done
echo " "
fi

Run script as follows to set a step value and generate a sequence:
$ chmod +x script
$ ./script 5 10 +
$ ./script 20 10 -

Tweet itFacebook itGoogle+ itPDF itFound an error/typo on this page?

Comments on this entry are closed.

  • Tariq Rashid September 26, 2006, 10:27 pm

    bash3 makes it easier and more portable…

    bash-3.00$ for i in {5..10}; do echo $i; done

  • nixCraft September 27, 2006, 8:08 pm

    Tariq

    Good to know that you are upto date with BASH information. I don’t have bash 3 installed here but I am sure it will work out.

    Appreciate your post.

  • seshadri sethi October 26, 2006, 11:07 am

    i want to know , how to print 100 files using shell script

  • nixCraft October 26, 2006, 2:40 pm

    cd /path/to/directory
    for f in *
    do
    lp -d printer-name $f
    done

    Or simple:
    cd /path/to/dir
    lp -d printer-name *.txt

  • mickRacky March 31, 2009, 4:11 pm

    printing the FIRST 100 files:

    cnt=0; for i in *; do if [ $cnt -lt 100 ]; then lp -d printer-name $i; fi; let cnt=cnt+1;done

  • dennis April 14, 2009, 7:55 am

    If you’re only printing 100 out of 10,000 files, you’ll be stuck in that loop for a while unless you break out of it:

    cnt=0; for i in *; do if [ $cnt -ge 100 ]; then break; else lp -d printer-name $i; fi; let cnt=cnt+1;done

  • Tomas Hajny August 12, 2009, 7:54 am

    If you have many (I mean _many_) files in that directory, asterisk expansion may break limits of the command line length; in that case, simple listing combined with head would probably do better:

    ls | head -n 100 | lp -d printer-name

  • Phil September 13, 2009, 4:53 pm

    This

    #!/bin/bash
    for ((a=1; a <= 5 ; a++))
    do
    echo "Welcome $i times"
    done

    should be

    #!/bin/bash
    for ((a=1; a <= 5 ; a++))
    do
    echo "Welcome $a times"
    done

  • saikumar October 12, 2011, 2:37 pm

    how to print numbers side by side

    i.e
    i got the output as
    1
    2
    3
    4
    5
    1
    2
    3
    4
    1
    2
    3
    1
    2
    1
    but i neeed the output as
    1 2 3 4 5
    1 2 3 4
    1 2 3
    1 2
    1
    how to do ths in shell scripting

    • Simon Xu March 19, 2012, 6:30 am
      a=({1..5})
      for i in {5..1}
      do
        echo ${a[*]:0:$i}
      done
      
  • Ramachandra October 27, 2011, 9:11 am

    above question shell script what u need output
    =========
    #!/bin/sh
    for ((i=5; i>=1; i– ))
    do
    for ((j=1; j<=i; j++ ))
    do
    echo -n "$i"
    done
    echo ""
    done
    ==============
    output
    55555
    4444
    333
    22
    1

  • Ramachandra October 27, 2011, 9:13 am

    saikumar did you got shell script for your query

    • Mann April 28, 2012, 7:55 am

      write a shell programm to generate the first ‘n’ terms of the following sqnce without using multiplication…
      1 2 4 8 16 32…..

  • pavium December 27, 2011, 9:07 am

    I continue to use the ‘outdated’ seq command because of an option you didn’t mention:

    The -w option gives a sequence of numbers with equal width, by adding leading zeros if necessary.

  • hal April 5, 2012, 7:41 am

    echo {1..100}

  • Dan Hurley April 19, 2012, 12:48 am

    And this is nice:
    echo 1{6..9} 2{0..5}
    16 17 18 19 20 21 22 23 24 25

  • Gumshan May 18, 2012, 4:44 am

    Can someone please edit this one,
    #!/bin/bash
    # Usage:
    # ./script 1 5 +
    # ./script 100 50 –
    # where START END +/-
    FROM=$1
    TO=$2
    ACTION=”$3″
    if [ “$ACTION” == “+” ];
    then
    while [ $FROM -le $TO ]
    do
    echo -n $FROM ” ”
    (( FROM++ ))
    done
    echo “”
    else
    while [ $FROM -ge $TO ]
    do
    echo -n $FROM ” ”
    (( FROM– ))
    done
    echo ” ”
    fi

    –instead of displaying it, it would be saved to a txt file. :)
    like this

    6001
    6002
    .
    I just need it for a dictionary file. Thank you.

  • Praseetha December 10, 2012, 12:44 pm

    Hi,

    I need to create a calling script(main.sh) which would call another script (sub.sh). REquirement is as under :

    a) The sub.sh has few parameters like -U(i.e. username) -P(i.e. password) – R(i.e uniqueid)
    b) The -R parameter in sub.sh script has to be unique everytime it is run. This has to be handled in the main.sh script.
    c) In main.sh I need to generate a sequence and pass that vaue to the unique ID parameter in sub.sh. Everytime it should pass a unique value to sub.sh and execute sub.sh.

    Kindly help

  • jeff January 18, 2014, 9:01 am

    Write script to find numbers as 50,40,30,20,10 using while loop

  • Rajalogeshwaran July 18, 2014, 8:39 am

    Please provide a script to print a numbers as 5,4,3,2,1.

    This is my program scripts, but the result got the numbers sequence not horizontally.

    numbers=5
    i=1
    while [ “$i” -le “$numbers” ]
    do
    echo “$i”
    i=$(( $i + 1 ))
    done

    • Kannan October 24, 2014, 5:35 pm

      The below command generates output as 5,4,3,2,1

      $ seq -s ‘,’ 5 -1 1

  • benjamin October 10, 2014, 9:03 am

    hello guys!
    i need php code to print this output
    1
    1
    1
    1

    2
    2
    2
    2

    3
    3
    3
    3

    up to 13 thx