IT story

while 루프 내에서 bash에서 입력 읽기

hot-time 2020. 9. 7. 21:26
반응형

while 루프 내에서 bash에서 입력 읽기


다음과 같은 bash 스크립트가 있습니다.

cat filename | while read line
do
    read input;
    echo $input;
done

그러나 이것은 내가 while 루프에서 읽을 때 가능한 I / O 리디렉션으로 인해 파일 파일 이름에서 읽으려고 할 때 올바른 출력을 제공하지 않습니다.

같은 일을하는 다른 방법이 있습니까?


제어 터미널 장치에서 읽습니다.

read input </dev/tty

더 많은 정보 : http://compgroups.net/comp.unix.shell/Fixing-stdin-inside-a-redirected-loop


일반 stdin을 유닛 3을 통해 리디렉션하여 파이프 라인 내부를 유지할 수 있습니다.

{ cat notify-finished | while read line; do
    read -u 3 input
    echo "$input"
done; } 3<&0

BTW, 정말로 cat이런 식으로 사용 하고 있다면 리디렉션으로 바꾸면 일이 훨씬 쉬워집니다.

while read line; do
    read -u 3 input
    echo "$input"
done 3<&0 <notify-finished

또는 해당 버전에서 stdin과 unit 3을 바꿀 수 있습니다. unit 3으로 파일을 읽고 stdin은 그대로 두십시오.

while read line <&3; do
    # read & use stdin normally inside the loop
    read input
    echo "$input"
done 3<notify-finished

다음과 같이 루프를 변경하십시오.

for line in $(cat filename); do
    read input
    echo $input;
done

단위 테스트 :

for line in $(cat /etc/passwd); do
    read input
    echo $input;
    echo "[$line]"
done

It looks like you read twice, the read inside the while loop is not needed. Also, you don't need to invoke the cat command:

while read input
do
    echo $input
done < filename

echo "Enter the Programs you want to run:"
> ${PROGRAM_LIST}
while read PROGRAM_ENTRY
do
   if [ ! -s ${PROGRAM_ENTRY} ]
   then
      echo ${PROGRAM_ENTRY} >> ${PROGRAM_LIST}
   else
      break
   fi
done

참고URL : https://stackoverflow.com/questions/6883363/read-input-in-bash-inside-a-while-loop

반응형