2017-11-30 1 views
0

다음 코드는 진행률 막대을 HTML 페이지에 표시합니다. 그것은 잘 실행되지만 코드의 많은 라인까지 소요됩니다.IF 문을 FOR 또는 WHILE로 변환 (쉘 스크립트)

질문 :
- 나는 그것의 기능을 복제하는 for 또는 while 루프에이 변환 가겠어요 어떻게? per_usage 값이 경우 41 % |||||

41이 사전에 감사처럼

if [ $per_usage -ge 1 ] && [ $per_usage -le 10 ] 
    then 
     indg="|" 
     indb="" 
     indr="" 
elif [ $per_usage -gt 10 ] && [ $per_usage -le 20 ] 
    then 
     indg="||" 
     indb="" 
     indr="" 
elif [ $per_usage -gt 20 ] && [ $per_usage -le 30 ] 
    then 
     indg="|||" 
     indb="" 
     indr="" 
elif [ $per_usage -gt 30 ] && [ $per_usage -le 40 ] 
    then 
     indg="||||" 
     indb="" 
     indr="" 
elif [ $per_usage -gt 40 ] && [ $per_usage -le 50 ] 
    then 
     indg="|||||" 
     indb="" 
     indr="" 
elif [ $per_usage -gt 50 ] && [ $per_usage -le 60 ] 
    then 
     indg="|||||" 
     indb="|" 
     indr="" 
elif [ $per_usage -gt 60 ] && [ $per_usage -le 70 ] 
    then 
     indg="|||||" 
     indb="||" 
     indr="" 
elif [ $per_usage -gt 70 ] && [ $per_usage -le 80 ] 
    then 
     indg="|||||" 
     indb="|||" 
     indr="" 
elif [ $per_usage -gt 80 ] && [ $per_usage -le 90 ] 
    then 
     indg="|||||" 
     indb="||" 
     indr="||" 
elif [ $per_usage -gt 90 ] 
    then 
     indg="" 
     indb="" 
     indr="||||||||||" 
else 
     indg="" 
     indb="" 
     indr="" 
fi 

예를 들어 내 출력됩니다.

답변

0

것은 이런 종류는 아주 쉽게 반복 할 수있다 :이 예에서

#!/bin/bash 

get_string() { 
    per_usage="$1" 
    if [ "$per_usage" -le 100 ] && [ "$per_usage" -ge 0 ]; then 
     echo -en "${per_usage}%\t" 
     bars=$(($per_usage/10 + 1)) 
     printf "%0.s|" $(seq 1 $bars) 
     echo 
    fi 
} 

i=0 
while [ "$i" -le 100 ]; do 
    string=$(get_string "$i") 
    echo "$string" 
    let i++ 
done 

을의 get_string 기능은 입력 수에 따라 문자열을 생성 할 수 있습니다. 예를 들어 get_string 4141% |||||을 인쇄합니다. 아래의 작은 while 루프에서는 0 - 100의 문자열이 $string 변수에 저장되어 인쇄됩니다.

bars은 인쇄 할 바의 수를 저장합니다. 10 % 당 하나의 술집. 그런 다음 printfseq|bars 횟수를 인쇄하는 데 사용됩니다.

이 기능을 사용하면 코드를 정리할 수 있습니다.

+0

답변 해 주셔서 감사합니다. 매력처럼 작동합니다. 나는이 코드를 내 프로그램에 맞출 수 있었다. 코드 "get_string() { per_usage ="$ 1 " ["$ per_usage "-le 100] && ["$ per_usage "-ge 0]; then echo -en "$ {per_usage} % \ t" bars = $ (($ per_usage/10)) printf "% 0.s |" $ (seq 1 $ bars) echo fi } –

+0

여러분을 환영합니다! 다행 이네. –