Bash에서 do-while 루프 에뮬레이션
Bash에서 do-while 루프를 에뮬레이트하는 가장 좋은 방법은 무엇입니까?
while
루프에 들어가기 전에 조건을 확인한 다음 루프 에서 조건 을 계속 다시 확인할 수 있지만 코드가 중복됩니다. 더 깨끗한 방법이 있습니까?
내 스크립트의 의사 코드 :
while [ current_time <= $cutoff ]; do
check_if_file_present
#do other stuff
done
시간이 check_if_file_present
지나면 실행되지 않으며 $cutoff
, 그 동안에는 수행되지 않습니다 .
두 가지 간단한 솔루션 :
while 루프 전에 코드를 한 번 실행
actions() { check_if_file_present # Do other stuff } actions #1st execution while [ current_time <= $cutoff ]; do actions # Loop execution done
또는:
while : ; do actions [[ current_time <= $cutoff ]] || break done
while
테스트 후 와 테스트 전에 루프의 몸체를 배치하십시오 . while
루프 의 실제 몸체 는 작동하지 않아야합니다.
while
check_if_file_present
#do other stuff
(( current_time <= cutoff ))
do
:
done
콜론 대신 continue
더 읽기 쉬운 것을 사용할 수 있습니다 . 또한 반복 사이 (첫 번째 또는 마지막이 아닌) 사이 에서만 실행되는 명령을 삽입 할 수도 있습니다 (예 :) echo "Retrying in five seconds"; sleep 5
. 또는 값 사이에 구분 기호를 인쇄하십시오.
i=1; while printf '%d' "$((i++))"; (( i <= 4)); do printf ','; done; printf '\n'
정수를 비교하는 것으로 보이므로 이중 괄호를 사용하도록 테스트를 변경했습니다. 이중 대괄호 안에는 <=
예를 들어 2와 10을 비교할 때 어휘와 같은 비교 연산자 가 잘못된 결과를 제공합니다. 이러한 연산자는 단일 대괄호 안에서 작동하지 않습니다.
콜론 대신 더 읽기 쉬운 경우 계속을 사용할 수 있습니다.
이 방법은 내가 찾던 Do-While 루프를 수행하는 방식을 모방하여 작업 후에 조건 테스트를 수행합니다. 또한 continue 문 대신 do 문 뒤에 인덱스 증분 (필요한 경우)을 둘 수 있음을 알았습니다.
while
check_if_file_present
#do other stuff
(( current_time <= cutoff ))
do
(( index++ ));
done
Bash에서 do-while 루프를 다음과 while [[condition]]; do true; done
같이 에뮬레이트 할 수 있습니다 .
while [[ current_time <= $cutoff ]]
check_if_file_present
#do other stuff
do true; done
예를 들어. bash 스크립트에서 ssh 연결 을 얻는 구현은 다음과 같습니다 .
#!/bin/bash
while [[ $STATUS != 0 ]]
ssh-add -l &>/dev/null; STATUS="$?"
if [[ $STATUS == 127 ]]; then echo "ssh not instaled" && exit 0;
elif [[ $STATUS == 2 ]]; then echo "running ssh-agent.." && eval `ssh-agent` > /dev/null;
elif [[ $STATUS == 1 ]]; then echo "get session identity.." && expect $HOME/agent &> /dev/null;
else ssh-add -l && git submodule update --init --recursive --remote --merge && return 0; fi
do true; done
다음과 같이 출력이 순서대로 제공됩니다.
Step #0 - "gcloud": intalling expect..
Step #0 - "gcloud": running ssh-agent..
Step #0 - "gcloud": get session identity..
Step #0 - "gcloud": 4096 SHA256:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX /builder/home/.ssh/id_rsa (RSA)
Step #0 - "gcloud": Submodule '.google/cloud/compute/home/chetabahana/.docker/compose' (git@github.com:chetabahana/compose) registered for path '.google/cloud/compute/home/chetabahana/.docker/compose'
Step #0 - "gcloud": Cloning into '/workspace/.io/.google/cloud/compute/home/chetabahana/.docker/compose'...
Step #0 - "gcloud": Warning: Permanently added the RSA host key for IP address 'XXX.XX.XXX.XXX' to the list of known hosts.
Step #0 - "gcloud": Submodule path '.google/cloud/compute/home/chetabahana/.docker/compose': checked out '24a28a7a306a671bbc430aa27b83c09cc5f1c62d'
Finished Step #0 - "gcloud"
참고 URL : https://stackoverflow.com/questions/16489809/emulating-a-do-while-loop-in-bash
'Programing' 카테고리의 다른 글
C #에서 자체 동적 형식 또는 동적 개체를 만드는 방법은 무엇입니까? (0) | 2020.07.12 |
---|---|
JavaScript에서 정수 범위 설정 (0) | 2020.07.12 |
페이지로드시 스크롤하여 ID로 애니메이션 (0) | 2020.07.12 |
문자열 유형으로 buildConfigField를 생성하는 방법 (0) | 2020.07.12 |
일련의 공백을 단일 문자로 축소하고 문자열 자르기 (0) | 2020.07.11 |