Created
August 25, 2016 16:18
-
-
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.
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 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