Skip to content

Instantly share code, notes, and snippets.

@sweenzor
Created March 1, 2012 06:35
Show Gist options
  • Save sweenzor/1947832 to your computer and use it in GitHub Desktop.
Save sweenzor/1947832 to your computer and use it in GitHub Desktop.
Index arrays in bash
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
array=(one two three)
count=${#array[@]}
index=0
while [ "$index" -lt "$count" ]; do
echo -e "index: $index\tvalue: ${array[$index]}"
let "index++"
done
#!/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