此代码不使用select
,但几乎可以满足您的需求-
#! /bin/bash
files=("file1" "file2" "file3" "file4" "Quit")
menuitems() {
echo "Avaliable options:"
for i in ${!files[@]}; do
printf "%3d%s) %s\n" $((i+1)) "${choices[i]:- }" "${files[i]}"
done
[[ "$msg" ]] && echo "$msg"; :
}
prompt="Enter an option (enter again to uncheck, press RETURN when done): "
while menuitems && read -rp "$prompt" num && [[ "$num" ]]; do
[[ "$num" != *[![:digit:]]* ]] && (( num > 0 && num <= ${#files[@]} )) || {
msg="Invalid option: $num"; continue
}
if [ $num == ${#files[@]} ];then
exit
fi
((num--)); msg="${files[num]} was ${choices[num]:+un-}selected"
[[ "${choices[num]}" ]] && choices[num]="" || choices[num]="x"
done
printf "You selected"; msg=" nothing"
for i in ${!files[@]}; do
[[ "${choices[i]}" ]] && { printf " %s" "${files[i]}"; msg=""; }
done
echo "$msg"
演示-
$ ./test.sh
Avaliable options:
1 ) file1
2 ) file2
3 ) file3
4 ) file4
5 ) Quit
Enter an option (enter again to uncheck, press RETURN when done): 1
Avaliable options:
1x) file1
2 ) file2
3 ) file3
4 ) file4
5 ) Quit
file1 was selected
Enter an option (enter again to uncheck, press RETURN when done): 2
Avaliable options:
1x) file1
2x) file2
3 ) file3
4 ) file4
5 ) Quit
file2 was selected
Enter an option (enter again to uncheck, press RETURN when done): 3
Avaliable options:
1x) file1
2x) file2
3x) file3
4 ) file4
5 ) Quit
file3 was selected
Enter an option (enter again to uncheck, press RETURN when done): 1
Avaliable options:
1 ) file1
2x) file2
3x) file3
4 ) file4
5 ) Quit
file1 was un-selected
Enter an option (enter again to uncheck, press RETURN when done):
You selected file2 file3