L
L
lekam2021-11-07 02:25:12
bash
lekam, 2021-11-07 02:25:12

How to create an array with leading zeros in Bash?

It would seem that what is easier:

#!/bin/bash

hr=(00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23)

for i in ${hr[@]}; do
echo ${hr[i]}
done

but it was not there:
[email protected]:$ ./stat.sh
00
01
02
03
04
05
06
07
./stat.sh: строка 7: 08: слишком большое значение для основания (неверный маркер «08»)

Bash thinks that if a number starts with 0, then it is in octal and the number 8 is not in it. What to do?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2021-11-07
@lekam

for i in ${hr[@]}; do
echo ${hr[i]}
done

Bash thinks that if a number starts with 0, then it is in octal and the number 8 is not in it. What to do?

Choose what exactly you have in the array - lines or indices. And if I chose lines, then do not interpret them here: as indexes. And if you chose indices, then follow the rules for writing numbers. I would do like this:echo ${hr[i]}
#!/bin/bash

hr=(00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23)

for i in ${hr[@]}; do
echo $i
done

S
Saboteur, 2021-11-07
@saboteur_kiev

There is no such thing as "a number with a leading zero".
The leading zero is not part of the number, but simply output formatting.
So just use printf with the format, in your case %02d (d is a number, 02 is 2 digits with a leading zero)

#!/bin/bash

hr=(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23)

for i in ${hr[@]}; do
printf "%02d\n" ${hr[i]}
done

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question