상세 컨텐츠

본문 제목

shell script로 checkbox 표현하기

shell script

by 빨간눈동자 2024. 6. 25. 22:21

본문

반응형

코드 참고.. 

 

checkbox.sh

더보기
#!/bin/bash

 

tput civis
echo -e "\033[6n"
read -sdR CURPOS
CURPOS=${CURPOS#*[}
ROW=${CURPOS%;*}
LINE=`tput lines`

 

options=("$@")
max="${#}"
current=0
update=1

 

for (( i=0 ; i<max ; i++ ));do
selected[${i}]=false
done

 

function keyboard(){
update=1
IFS= read -r -sn1 t
if [[ $t == A ]]; then
[[ "$current" == "0" ]] || current=$((current - 1))
elif [[ $t == B ]]; then
[[ "$current" == "$1" ]] || current=$((current + 1))
elif [[ $t == " " ]];then
[[ "${selected[${current}]}" == false ]] && selected[${current}]=true || selected[${current}]=false
elif [[ $t == "" ]];then
return 1
else
update=0
fi
}

 

function display(){
if [ $(($ROW+$max)) -le $LINE ];then
tput cup $ROW 0
fi

 

for (( i=0 ; i<max ; i++ )); do
if [[ ${current} == "${i}" && ${selected[${i}]} == true ]];then
printf "\e[0;90m[\e[0;92m*\e[0;90m] \e[0m\e[0;92m%s\e[0m\n" "${options[$i]}"
elif [[ ${current} == "${i}" && ${selected[${i}]} == false ]];then
printf "\e[0;90m[ ] \e[0m\e[0;92m%s\e[0m\n" "${options[$i]}"
elif [[ ${selected[${i}]} == true ]];then
printf "\e[0;90m[\e[0;92m*\e[0;90m] \e[0m\e[1;77m%s\e[0m\n" "${options[$i]}"
elif [[ ${selected[${i}]} == false ]];then
printf "\e[0;90m[ ] \e[0m\e[1;77m%s\e[0m\n" "${options[$i]}"
fi
done
if [ $(($ROW+$max)) -gt $LINE ];then
for (( i=0 ; i<$max ; i++ )); do
tput cuu1
done
fi
}

 

while true; do
if [[ $update -eq 1 ]];then
display "$@"
fi
keyboard $((max-1))
if [[ $? -eq 1 ]]; then
no_selected=true
for (( i=0 ; i<max ; i++ )); do
if [[ ${selected[$i]} == true ]]; then
no_selected=false
fi
done
if [ $no_selected == true ]; then
continue
fi
if [ $(($ROW+$max)) -gt $LINE ];then
tput cup $ROW 0
tput cnorm
fi
break
fi
done

 

current=-1
export selected # used in lupa_envsetup.sh
export max # used in lupa_envsetup.sh

 

example.sh

더보기
#!/bin/bash

 

option=("Option 1" "Option 2" "Option 3" "Option 4" "Option 5")
source checkbox.sh "${option[@]}"

 

printf "\n[ "
for (( i=0 ; i<max ; i++ )); do
if [[ ${selected[$i]} == true ]]; then
printf "${option[$i]} "
fi
done
printf "] is selected\n"

 

사용 예시

./example.sh

 

 

출처 내용을 기반으로 오동작하는 부분 추가 수정함. 

 

 

출처 : https://github.com/HadiDotSh/bash-checkbox

반응형

관련글 더보기