简体   繁体   中英

bash scripting language print a list of numbers using a loop

I want to print in a text file (numberlist.txt), using bash, all the numbers from 000000 to 999999, one number in each line. Example:

000000
000001
000002

...

999999

This is my code: (WHEN I RUN IT NOTHING HAPPENS)

#!/bin/bash 
CONT=0
MAX_NUM=1000000
FILE_NAME=numberlist.txt

#While counter CONT is lower than MAX_NUM (-lt, “lower #than”) the loop is executed
until [ $CONT -lt $MAX_NUM ]; do
     printf "%000002d\n" $CONT > $FILE_NAME
     #CONT= CONT + 1
     let CONT+=1
done

What am I doing wrong?

Instead of opening and closing the file a million times, do it just once by redirecting the output of the loop instead of the printf:

#!/bin/bash 
CONT=0
MAX_NUM=1000000
FILE_NAME=numberlist.txt

while [ $CONT -lt $MAX_NUM ]; do
     printf "%06d\n" $CONT 
     #CONT= CONT + 1
     let CONT++
done > $FILE_NAME

Converting the comments from pasaba por aqui as answer.:

#!/bin/bash 
CONT=0
MAX_NUM=1000000
FILE_NAME=numberlist.txt

#While counter CONT is lower than MAX_NUM (-lt, “lower #than”) the loop is executed
while [ $CONT -lt $MAX_NUM ]; do
     printf "%06d\n" $CONT >>$FILE_NAME
     #CONT= CONT + 1
     let CONT++
done

If you use bash version 4 at least you can do simply

echo -en {000000..999999}'\n' > numberlist.txt

No need for loops. The -en and the \\n are to put each number on its own line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM