programing

루프 내의 사용자 입력 읽기

javajsp 2023. 4. 19. 22:14

루프 내의 사용자 입력 읽기

나는 다음과 같은 bash 스크립트를 가지고 있다.

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

I/O 리다이렉션이 가능하기 때문에 파일 파일 이름에서 읽으려고 하는 동안 루프에서 읽었을 때 올바른 출력을 얻을 수 없습니다.

같은 일을 할 다른 방법은요?

제어 단말 장치에서 판독:

read input </dev/tty

상세정보 : http://compgroups.net/comp.unix.shell/Fixing-stdin-inside-a-redirected-loop

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

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

참고로, 만약 당신이 정말로 이 제품을 사용하고 있다면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

이 파라미터 -u를 read와 함께 찾았습니다.

"-u 1"은 "stdout에서 읽기"를 의미합니다.

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)

두 번 읽은 것 같은데 while loop 내부는 읽을 필요가 없습니다.또한 cat 명령어를 호출할 필요도 없습니다.

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-user-input-inside-a-loop