카운트다운 타이머를 만드는 방법

카운트다운 타이머를 만드는 방법

20 sec카운트다운 타이머를 에서 내림차순으로 표시해야 합니다 .00 sec

20초 이내에 비밀번호를 입력하지 못하면 메시지와 함께 종료됩니다.너의 시간은 끝났어

산출:

you have 20 sec to enter password :
you have 15 sec to enter password :
you have 10 sec to enter password :
you have 00 sec to enter password :

메시지를 표시하는 작업 코드의 일부

read -t 20 -p 'Enter your password : ' 
status=$?   
if [ $status -eq 142 ]
then
    echo "your time is over"
fi

답변1

누군가가 더 나은 해결책을 찾을 때까지:

#!/bin/bash

tmout=20

(
        while [[ $tmout -gt 0 ]]; do
                printf '\rPlease respond within %02d seconds: ' "$tmout" >&2
                sleep 1
                tmout=$(( tmout - 1 ))
        done
) & prompt_pid=$!

read -s -t "$tmout"
read_ok=$?
echo ''

if [[ $read_ok -eq 0 ]]; then
        kill "$prompt_pid"
        printf 'You responded with "%s"\n' "$REPLY"
else
        echo 'You did not respond in time'
fi

$tmout그러면 몇 초 동안 또는 종료될 때까지 매초마다 프롬프트를 업데이트하는 백그라운드 작업이 시작됩니다 . 프롬프트 텍스트 앞에 캐리지 리턴 문자가 있습니다 \r. \r를 사용하여 출력하면 printf커서가 줄의 시작 부분으로 다시 이동합니다. 즉, 문자열의 나머지 부분이 이전에 출력된 텍스트를 덮어쓰며 똑딱거리는 카운터처럼 보입니다. 출력 텍스트 문자열이 printf항상 같은 길이가 되도록 의도적으로 0으로 채워진 두 자리 정수를 카운터로 사용합니다(적어도 $tmout100보다 작은 값의 경우).

그런 다음 포그라운드 작업은 시간 초과를 사용하여 $tmout사용자 입력을 몇 초간 기다립니다. read여기서는 비밀번호를 읽기 때문에 -s사용 read합니다(이는 입력한 내용이 표시되지 않으며 출력 프롬프트에 의해 복잡해지지 않는다는 의미이기도 함).

반환 시 read프롬프트 루프를 종료하고(아직 실행 중인 경우) read종료된 방식에 따라 메시지를 인쇄합니다.

답변2

다음은 스니펫입니다. 00초에 도달하면 5초를 더 기다립니다. 이것이 원하는 동작인지는 알 수 없으므로 조건을 사용하여 편집할 수 있습니다.

#!/bin/bash
c1=5
c2=4
count=20
status=''
while [[ "$count" != 0 ]]   
    do
        count="$(expr $c1 \* $c2)"
        c2="$(expr $c2 \- 1)"
        read -t 5 -p  "You have $count sec to enter your password : "$'\n'
        status=$?
        if [ "$status" -ne 142 ] ; then
          break
        fi

done
if [ "$status" -eq 142 ]
then
    echo "Your time is over"
    
else 
   echo "Success"
fi 

###편집하다###

출력 1:

[root@host~]# ./lol.sh
You have 20 sec to enter your password :
You have 15 sec to enter your password :
You have 10 sec to enter your password :
You have 5 sec to enter your password :
You have 0 sec to enter your password :
Your time is over

출력 2:

[root@host~]# ./lol.sh
You have 20 sec to enter your password :
LOL
Success
[root@host~]#

## 댓글에서 제안된 대로 2개의 글로벌 솔루션을 추가로 편집합니다. ##:

이를 위해 카운터는 정확히 20초로 변경할 수 있습니다.TMT&잠깐만 기다려편리한 상수.

#!/bin/bash
##CALCULATTION :
##TIMEOUT=WAIT_SECONDS * NB_ITERATIONS 
##TIMEOUT modulo WAIT_SECONDS should  equal to 0 to get a fixed iterations number
# 20  =   5 * 4 
wait_sec=5
tmt=20
modulo_ok=1
fpr=1
count="$tmt"
# Modulo Test
if [[ "$(($tmt % $wait_sec))" -eq 0 ]]; then
    nb_iters="$(expr $tmt \/ $wait_sec)"
    modulo_ok=0
fi
if [[ "modulo_ok" -eq 0 ]]; then
    (while [[ "$count" != 0 ]] && [[ "$fpr" -gt 0 ]]
        do
            count="$(expr $wait_sec \* $nb_iters)"
            nb_iters="$(expr $nb_iters \- 1)"
            echo "You have $count sec to enter your password :" 
            ps -p "$pid" &> /dev/null 
            sleep $wait_sec
    done
    ) &  fpr=$?  
    bpr=$!
    read -t "$tmt" -s pass
    kill $bpr > /dev/null 2>&1 
    if [[ -z  "$pass" ]]
    then
        echo "Your time is over"
    else 
       echo "Success"
       echo "Your password is : $pass"
    fi 
else 
    echo 'Timeout modulo Wait seconds should be equal to 0'
fi

출력 3: CASE -> tmt 간격 동안 비밀번호가 설정됨

[root@host~]# ./lol2.sh
You have 20 sec to enter your password :
You have 15 sec to enter your password :
Success
Your password is : Reda

출력 4:케이스->타임아웃

[root@host~]# ./lol2.sh
You have 20 sec to enter your password :
You have 15 sec to enter your password :
You have 10 sec to enter your password :
You have 5 sec to enter your password :
Your time is over

출력 5:CASE -> tmt % wait_sec가 0이 아닙니다.

[root@host~]# ./lol2.sh
Timeout modulo Wait seconds should be equal to 0

관련 정보