-
-
Save sweenzor/1947832 to your computer and use it in GitHub Desktop.
Index arrays in bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function search_array() { | |
index=0 | |
while [ "$index" -lt "${#myArray[@]}" ]; do | |
if [ "${myArray[$index]}" = "$1" ]; then | |
echo $index | |
return | |
fi | |
let "index++" | |
done | |
echo "" | |
} | |
myArray=(one two three) | |
value="one" | |
index=$(search_array $value) | |
if [ -z "$index" ]; then | |
echo -e "the value \"$value\" is not in \$myArray" | |
else | |
echo -e "the value \"$value\" was found at index: $index" | |
fi |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
array=(one two three) | |
count=${#array[@]} | |
index=0 | |
while [ "$index" -lt "$count" ]; do | |
echo -e "index: $index\tvalue: ${array[$index]}" | |
let "index++" | |
done |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
array[5]="tom" | |
array[13]="jenny" | |
array[77]="julie" | |
echo ${!array[*]} # find all the indexes | |
# print all indexes and associated values | |
for I in ${!array[*]}; do | |
echo $I: ${array[$I]} | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment