Unix shell do support array. Yes, it does.
Please refer to
https://opensource.com/article/18/5/you-dont-know-bash-intro-bash-arrays OR
https://www.tutorialspoint.com/unix/unix-using-arrays.htm for more info on this.
To define an array, do;
myArray=(the quick brown fox jumps over the lazy dog)
But how to read an array?. Lets try this;
#!/bin/bash
myArray=(the quick brown fox jumps over the lazy dog)
echo $myArray
Run it ...
# ./test.sh
the
It will only echo the 1st word from the array.
Lets try another example.
#!/bin/bash
myArray=(the quick brown fox jumps over the lazy dog)
echo ${myArray[0]}
echo ${myArray[1]}
echo ${myArray[2]}
echo ${myArray[3]}
echo ${myArray[4]}
echo ${myArray[5]}
echo ${myArray[6]}
echo ${myArray[7]}
echo ${myArray[8]}
echo ${myArray[9]}
Run it ...
# ./test.sh
the
quick
brown
fox
jumps
over
the
lazy
dog
Now, It will print all array content.
Note that, it won't give any alert if the index is out of bound, for this example = "${myArray[9]}"
Lets do a proper way to read an array by using "for loop";
#!/bin/bash
myArray=(the quick brown fox jumps over the lazy dog)
for i in ${myArray[@]}
do
echo $i
done
Run it ...
# ./test.sh
the
quick
brown
fox
jumps
over
the
lazy
dog
You will get above output.
Adding an "!" to the array name will change the loop from looping through the values to looping through the indices.
#!/bin/bash
myArray=(the quick brown fox jumps over the lazy dog)
for i in ${!myArray[@]}
do
echo $i
done
Run it ...
# ./test.sh
0
1
2
3
4
5
6
7
8
Example below is using "while loop" to loop through the array.
#!/bin/bash
myArray=(the quick brown fox jumps over the lazy dog)
index=0
while [ $index -lt ${#myArray[@]} ]
do
echo $index = ${myArray[index]}
index=`expr $index + 1`
done
Run it ...
# ./test.sh
0 = the
1 = quick
2 = brown
3 = fox
4 = jumps
5 = over
6 = the
7 = lazy
8 = dog
Here are some syntax list that might be useful.
Syntax |
Result |
myArray=() |
Create an empty array |
myArray=(1 2 3) |
Initialize array |
${myArray[2]} |
Retrieve all elements |
${myArray[@]} |
Retrieve all elements |
${!myArray[@]} |
Retrieve array indices |
${#myArray[@]} |
Calculate array size |
myArray[0]=3 |
Overwrite 1st element |
myArray+=(4) |
Append value(s) |
${arr[@]:s:n} |
Retrieve n elements starting at index s |
No comments:
Post a Comment