#!/bin/bash
values=( "Why is" "a raven" "like a" "writing desk?" )
select word in "${values[@]}"; do
if [[ -z "$word" ]]; then
printf '"%s" is not a valid choice\n' "$REPLY" >&2
else
user_in="$(( REPLY - 1 ))"
break
fi
done
for (( i = 0; i < ${#values[@]}; ++i )); do
if (( i != user_in )); then
printf 'You did not pick "%s"\n' "${values[$i]}"
fi
done
The select
command will present the user with a menu of choices. Upon picking a menu item, $REPLY
will be the number that the user entered, and $word
will be the value in the menu corresponding to that number. If an invalid choice is made, $word
will be empty.
The second part iterates over our array (which corresponds to your $USER_INPUT
string) using the C-like for
loop in bash
. If we come upon the index that the corresponds to the chosen value, we skip it. We print out all other values from our array.
You may obviously execute commands in the loop to:
for (( i = 0; i < ${#values[@]}; ++i )); do
if (( i != user_in )); then
printf 'command %s %s\n' "$user_in" "${values[$i]}"
fi
done
or even
for (( i = 0; i < ${#values[@]}; ++i )); do
if (( i != user_in )); then
command "${values[$user_in]}" "${values[$i]}"
fi
done
which will try to run the actual things in $values
as a command.
Testing it (with the first version of the loop):
$ bash script.sh
1) Why is
2) a raven
3) like a
4) writing desk?
#? B
"B" is not a valid choice
#? 0
"0" is not a valid choice
#? 3
You did not pick "Why is"
You did not pick "a raven"
You did not pick "writing desk?"
If you can afford to modify $values
, and just want to output the things that the user didn't pick, then the second part of the script (the loop) may be replaced with
unset values[$user_in]
printf 'You did not pick "%s"\n' "${values[@]}"