Monday, April 19, 2021
Bash array - how to use arrays in Unix shell
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 $myArrayRun it ...
# ./test.sh theIt 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 dogNow, 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 doneRun it ...
# ./test.sh the quick brown fox jumps over the lazy dogYou 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 doneRun it ...
# ./test.sh 0 1 2 3 4 5 6 7 8Example 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` doneRun it ...
# ./test.sh 0 = the 1 = quick 2 = brown 3 = fox 4 = jumps 5 = over 6 = the 7 = lazy 8 = dogHere 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 |
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment