Reading input in bash inside while loop

I have a bash script, something like the following,

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

but this obviously does not give me the correct result, as when I read in a while loop that it is trying to read from the file name of the file due to a possible I / O redirection.

Any other way to do the same?

+66
bash while-loop
Jul 30 '11 at 13:22
source share
5 answers

Reading from the control terminal device:

 read input </dev/tty 

Additional information: http://compgroups.net/comp.unix.shell/Fixing-stdin-inside-a-redirected-loop

+73
Jul 30 2018-11-11T00:
source share

You can redirect the standard stdin through module 3 to save it inside the pipeline:

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

By the way, if you really use cat in this way, replace it with redirection, and everything will become even simpler:

 while read line; do read -u 3 input echo "$input" done 3<&0 <notify-finished 
+44
Jul 31 '11 at 4:44
source share

Try changing the loop as follows:

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

Unit test:

 for line in $(cat /etc/passwd); do read input echo $input; echo "[$line]" done 
+6
Jul 30 2018-11-11T00:
source share

It looks like you are reading twice, reading inside the while loop is not required. In addition, you do not need to call the cat command:

 while read input do echo $input done < filename 
+4
Jul 30 '11 at 13:32
source share
 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 
-5
Jun 04 '14 at 6:25
source share



All Articles