How to initiate array element to 0 in bash?
Your example will declare/initialize an empty array.
If you want to initialize array members, you do something like this:
declare -a MY_ARRAY=(0 0 0 0) # this initializes an array with four members
If you want to initialize an array with 100 members, you can do this:
declare -a MY_ARRAY=( $(for i in {1..100}; do echo 0; done) )
Keep in mind that arrays in bash are not fixed length (nor do indices have to be consecutive). Therefore you can't initialize all members of the array unless you know what the number should be.
How to create an array with leading zeros in Bash?
Use brace expansion (ranges, repetition).
To create an array:
hours=({00..23})
Loop through it:
for i in "${hours[@]}"; do
echo "$i"
done
Or loop through a brace expansion:
for i in {00..23}; do
echo "$i"
done
Regarding your error, it's because in bash arithmetic, all numbers with leading zeroes are treated as octals, and 08 and 09 are invalid octal numbers. All indexed array subscripts are evaluated as arithmetic expressions. You can fix the problem by using the notation base#number
to specify a number system. So for base 10: 10#09
, or for i=09
, 10#$i
. The variable must be prefixed with $
, 10#i
does not work.
You should be printing your array like this anyway:
Loop through elements:
for i in "${hr[@]}"; do
echo "$i"
done
Loop through indexes:
for i in "${!hr[@]}"; do
echo "index is $i"
echo "element is ${hr[i]}"
done
If you need to do arithmetic on the hours, or any zero padded number, you will lose the zero padding. You can print it again with printf: printf %.2d "$num"
, where 2
is the minimum width.
Create an array with a sequence of numbers in bash
Using seq
you can say seq FIRST STEP LAST
. In your case:
seq 0 0.1 2.5
Then it is a matter of storing these values in an array:
vals=($(seq 0 0.1 2.5))
You can then check the values with:
$ printf "%s\n" "${vals[@]}"
0,0
0,1
0,2
...
2,3
2,4
2,5
Yes, my locale is set to have commas instead of dots for decimals. This can be changed setting LC_NUMERIC="en_US.UTF-8"
.
By the way, brace expansion also allows to set an increment. The problem is that it has to be an integer:
$ echo {0..15..3}
0 3 6 9 12 15
How to set a range of array elements in bash
You can use eval
here, in this manner:
eval MY_ARRAY[{12..25}]=1\;
If you want to know what is being eval
ed, replace eval
by echo
.
Using eval
is generally considered as a no-no. But this use of eval here should be completely safe.
On another note,
for i in {1..100}; do echo 0; done
can also be re-written as
printf '%.1s\n' 0{1..100}
EDIT: For start & end being stored in variables, this could work:
$ declare -i start=12
$ declare -i end=12
$ eval $(eval echo "MY_ARRAY[{$start..$end}]=1;")
But in that case, you should really use loops. This answer is only for demonstration/information.
Shell Script: correct way to declare an empty array
Run it with bash:
bash test.sh
And seeing the error, it seems you're actually running it with dash:
> dash test.sh
test.sh: 5: test.sh: Syntax error: "(" unexpected
Only this time you probably used the link to it (/bin/sh -> /bin/dash).
Add a new element to an array without specifying the index in Bash
Yes there is:
ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')
Bash Reference Manual:
In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to the variable's previous value.
Also:
When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum index (for indexed arrays)
Behavior of Arrays in bash scripting and zsh shell (Start Index 0 or 1?)
Arrays in Bash are indexed from zero, and in zsh they're indexed from one.
But you don't need the indices for a simple use case such as this. Looping over ${array[@]}
works in both:
files=(file*)
for f in "${files[@]}"; do
echo "$f"
done
In zsh you could also use $files
instead of "${files[@]}"
, but that doesn't work in Bash. (And there's the slight difference that it drops empty array elements, but you won't get any from file names.)
Also, don't use $(ls file*)
, it will break if you have filenames with spaces (see WordSpliting on BashGuide), and is completely useless to begin with.
The shell is perfectly capable of generating filenames by itself. That's actually what will happen there, the shell finds all files with names matching file*
, passes them to ls
, and ls
just prints them out again for the shell to read and process.
Using the array name without an index gets the first array element in Bash, ok?
This is a documented behavior:
Referencing an array variable without a subscript is equivalent to referencing with a subscript of 0.
However, I recommend you still use the subscript, to make your code clearer.
How to extract a particular element from an array in BASH?
This is one of many ways
set ${myarr[2]}
echo $3
Related Topics
Sort Logs by Date Field in Bash
Increase of Virtual Memory Without Increse of Vmsize
Which Jdk's Distributions Can Run 'Javac -Source 1.6 -Target 1.5'
Docker Alpine Executable Binary Not Found Even If in Path
Apache Server Keeps Crashing, "Caught Sigterm, Shutting Down"
Sed: -I May Not Be Used with Stdin on MAC Os X
Renaming a Set of Files to 001, 002,
Unix 'Alias' Fails with 'Awk' Command
How to Check Fips 140-2 Support in Openssl
How to Specify Non-Capturing Groups in Sed
How to Create Opengl Context via Drm (Linux)
Get Link Speed Programmatically
How Is the Address of the Text Section of a Pie Executable Determined in Linux
Possible Values for 'Uname -M'
Binary Data Over Serial Terminal
Openssl Encoding Errors While Converting Cer to Pem