Skip to content

Instantly share code, notes, and snippets.

@kodie
Created August 25, 2016 16:18
Show Gist options
  • Save kodie/74b4e2aa0e9b976c33a42028a58d2412 to your computer and use it in GitHub Desktop.
Save kodie/74b4e2aa0e9b976c33a42028a58d2412 to your computer and use it in GitHub Desktop.
Searches array for a string and returns it's position/key if found.
function arraySearch {
local i
local output
local a=("$@")
local last_idx=$((${#a[@]} - 1))
local b=${a[last_idx]}
unset a[last_idx]
for i in "${!a[@]}" ; do
if [ "${a[$i]}" == "$b" ]; then
output=$i
fi
done
echo $output
}
# Example
array=("test1" "test2" "test3" "test4")
key=$(arraySearch "${array[@]}" "test3")
echo $key
# Output: 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment