Last active
January 10, 2018 09:29
-
-
Save suewonjp/6da63843cc7f9298192e20a77033ee49 to your computer and use it in GitHub Desktop.
General Bash function that creates selection interface from arbitrary array (See comment below for usage example)
This file contains hidden or 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
selectFromArray() { | |
if [ "$1" ]; then | |
local IFS=$'\n' selected= idx=$2 tmp=() | |
eval "local arr=( \${$1[*]} )" | |
if [ ${#arr[@]} -eq 1 ]; then | |
selected="${arr[0]}" | |
elif [ ${#arr[@]} -gt 1 ]; then | |
select a in "QUIT!" "${arr[@]}"; do | |
[ "${a}" = "QUIT!" ] && break | |
selected="${a}" | |
break | |
done | |
fi | |
if [ "${idx}" ]; then | |
unset IFS | |
read -ra tmp <<< "${selected}" | |
[ "${idx}" -lt "${#tmp[@]}" ] && echo "${tmp[$idx]}" | |
else | |
[ "${selected}" ] && echo "${selected}" | |
fi | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example