[bash] 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


답변

두 번 읽은 것처럼 보이지만 while 루프 내부에서 읽을 필요가 없습니다. 또한 cat 명령을 호출 할 필요가 없습니다.

while read input
do
    echo $input
done < filename


답변

이 매개 변수 -u를 읽었습니다.

“-u 1″은 “표준 입력에서 읽기”를 의미합니다.

while read -r newline; do
    ((i++))
    read -u 1 -p "Doing $i""th file, called $newline. Write your answer and press Enter!"
    echo "Processing $newline with $REPLY" # united input from two different read commands.
done <<< $(ls)


답변

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


답변