Skip to content

Instantly share code, notes, and snippets.

@Hayao0819
Created October 19, 2022 06:40
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hayao0819/487c426a694f2cad228d085c5d2191e1 to your computer and use it in GitHub Desktop.
Save Hayao0819/487c426a694f2cad228d085c5d2191e1 to your computer and use it in GitHub Desktop.
メニューに使えるシェル関数。外部依存はありません。
SelectMenu(){
local CaptureSpecialKeys Choices=("$@") CurrentChoice=0 Key=""
CaptureSpecialKeys(){
local SELECTION rest
IFS= read -r -n1 -s SELECTION
#echo "$SELECTION" | hexdump >&2
if [[ $SELECTION == $'\x1b' ]]; then
read -r -n2 -s rest
SELECTION+="$rest"
else
if [[ "$SELECTION" == '' ]] ;then
echo "Enter"
return 0
else
read -r rest
echo "$SELECTION$rest"
return 0
fi
fi
case $SELECTION in
$'\x1b\x5b\x41') #up arrow
echo "Up"
;;
$'\x1b\x5b\x42') #down arrow
echo "Down"
;;
$'\x1b\x5b\x43') #right arrow
echo "Right"
;;
$'\x1b\x5b\x44') #left arrow
echo "Left"
;;
$'\x20') #space
echo "Space"
;;
esac
}
#-- ここからメニュー
while [[ "$Key" != "Enter" ]]; do
# メニューを表示
for i in "${!Choices[@]}"; do
if [[ "$i" = "$CurrentChoice" ]]; then
printf "\033[4m" && printf "\033[1m" # 太字+下線
echo " > $i: ${Choices[$i]}"
else
echo " $i: ${Choices[$i]}"
fi
printf "\033[0m" # リセット
done
# キー検知
Key="$(CaptureSpecialKeys)"
case "$Key" in
Up)
(( "$CurrentChoice" != 0 )) && CurrentChoice=$((CurrentChoice - 1))
;;
Down)
(( "$CurrentChoice" != "${#Choices[@]}" - 1 )) && CurrentChoice=$((CurrentChoice + 1))
;;
esac
# メニューを削除
# shellcheck disable=SC2034
for i in $(seq 1 "${#Choices[@]}"); do
printf "\033[1A"
printf "\033[2K"
done
done
echo "${Choices[$CurrentChoice]}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment