I am trying to write a shell script that does this:
Takes input 4
and prints:
0000
0001
0002
until
9999
Thank you in advance.
I am trying to write a shell script that does this:
Takes input 4
and prints:
0000
0001
0002
until
9999
Thank you in advance.
You can use seq
to generate a series of numbers between a start and stop value with a printf
format string:
width=4
start=1
stop=9999
seq -f "%0${width}g" "$start" "$stop"
0001
0002
0003
0004
...
9997
9998
9999
If your OS is one of the super rare ones that does not include seq
(which is not a POSIX requirement) you can use awk
which is a POSIX requirement:
awk -v w="$width" -v start="$start" -v stop="$stop" 'BEGIN{
for(i=start;i<=stop;i++) printf("%0*d\n", w, i)}'
Or use bc
to replace seq
and xargs
to call printf
in pipe:
echo "for (i = $start; i <= $stop; i+=1) i" | bc -l | xargs printf "%0${width}d\n"
Or, Bash or similar only, a C style loop:
for (( i=${start}; i<=${stop}; i++ )); do
printf "%0*d\n" "$width" "$i"
done
Or, any POSIX shell, a while loop:
cnt="$start"
while [ "$cnt" -le "$stop" ]; do
printf "%0*d\n" "$width" "$cnt"
let cnt++
done
Your superpower here is printf
with the correct format.
for
loop to iterate over desired range.printf
to format the number of digits you want to print.The solution for your question is
#!/bin/bash
read -p "Enter the number of digits: " num_digits
START=0
STOP=9999
for((i=${START};i<=${STOP};i++))
do
printf '%0'${num_digits}'d\n' $i
done
Save this file and execute it. When prompted for number of digits, enter the number of digits you want to the output to be formatted.