3

I'm making a bash script in which I need to print a number while it's incremented like this:

0000
0001
0002
0003
0004

I have made this but is not working:

#!/bin/bash
i=0
pass[0]=0
pass[1]=0
pass[2]=0
pass[3]=0
for i in $(seq 1 9)
    pass[3]="$i"
    echo ${pass[*]}
done

I paste the script on cli and i get this.

$ ~ #!/bin/bash
$ ~ i=0
$ ~ pass[0]=0
$ ~ pass[1]=0
$ ~ pass[2]=0
$ ~ pass[3]=0
$ ~ for i in $(seq 1 9)
>     pass[3]="$i"
bash: error sintáctico cerca del elemento inesperado `pass[3]="$i"'
$ ~     echo ${pass[*]}
0 0 0 0
$ ~ done
bash: error sintáctico cerca del elemento inesperado `done'
$ ~ 
3
  • Do the values have to be in an array or can you just generate them as needed? Commented Nov 26, 2012 at 17:16
  • 1
    Your for i in ... is missing the corresponding do - e.g. for i in $(seq 1 9); do pass[3]="$i"; done Commented Nov 26, 2012 at 17:25
  • there are many ways to accomplish this task, but to make the least changes and answer what is wrong with your code, you forgot 'do' after the for expression. Commented Nov 26, 2012 at 17:26

4 Answers 4

6

Use this pure bash script:

for ((i=0; i<10; i++)); do
   printf "%04d\n" $i
one

OUTPUT:

0000
0001
0002
0003
0004
0005
0006
0007
0008
0009
Sign up to request clarification or add additional context in comments.

3 Comments

+1 but one can also do for i in {1..10}; do printf "%04d\n" $i; done. Not sure which style of for-loop is better; I just like expansion.
@RayToal: I just prefer for ((i=0; i<10; i++)); because it also accepts variable like N=10; for ((i=0; i<N; i++)); as well.
Yes definitely more flexible in general.
2
#!/bin/bash
i=0
pass[0]=0
pass[1]=0
pass[2]=0
pass[3]=0
for i in $(seq 1 9)
do
    pass[3]="$i"
    echo ${pass[*]}
done

did you forget 'do'

2 Comments

That's a very inefficient way of doing it. Prefer anubhava's answer.
@gniourf_gniourf as do I. but I was addressing why his sample code was not working. He had excluded the do
2

For those of you who like expansions, you can also do:

printf "%s\n" {0001..0009}

or

printf "%.4d\n" {1..9}

No loop!

You can store in an array thus:

$ myarray=( {0001..0009} )
$ printf "%s\n" "${myarray[@]}"
0001
0002
0003
0004
0005
0006
0007
0008
0009
$ echo "${myarray[3]}"
0004

Comments

1

You can do the formatting with seq:

seq -w 0000 0010

(if you don't like the {0000..0010} notation, which is more efficient but doesn't allow parameter substitution.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.