Skip to content

Instantly share code, notes, and snippets.

@suewonjp
Last active January 10, 2018 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suewonjp/6da63843cc7f9298192e20a77033ee49 to your computer and use it in GitHub Desktop.
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)
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
}
@suewonjp
Copy link
Author

Example

When you quite don't know Bash select built-in command, type help select at your terminal

### Create a Bash array
$ arr=(foo bar baz)

### Call the function ( Notice that the array variable doesn't use $ symbol! )
$ selectFromArray arr

### That will let you choose something in the array or nothing. 
### Choose 0 or 1 and the selection will abort
1) QUIT!
2) foo
3) bar
4) baz
#? 0

### E.g., choose 3 and you'll get 'bar'
$ selectFromArray arr
1) QUIT!
2) foo
3) bar
4) baz
#? 3
bar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment