Substitution of the input process bash / zsh gives a syntax error in combination with while

They work fine and do what they need (print the contents of the foo file):

cat <foo while read line; do echo $line; done <foo cat <(cat foo) 

However, this gives me a syntax error in zsh:

 zsh$ while read line; do echo $line; done <(cat foo) zsh: parse error near `<(cat foo)' 

and bash:

 bash$ while read line; do echo $line; done <(cat foo) bash: syntax error near unexpected token `<(cat foo)' 

Does anyone know the reason and possibly the workaround?

Note. This is obviously a toy example. In real code, I need the body of the while loop to execute in the main shell process, so I cannot just use

 cat foo | while read line; do echo $line; done 
+4
source share
3 answers

You need to redirect the process substitution to the while loop:

You wrote

 while read line; do echo $line; done <(cat foo) 

You need

 while read line; do echo $line; done < <(cat foo) # ...................................^ 

Consider process substitution as a file name.

+6
source

bash / zsh replaces <(cat foo) with a channel (file type), named as /dev/fd/n , where n is the file descriptor (number).

You can check the pipe name with the echo <(cat foo) .

As you know, bash / zsh also runs the cat foo command in another process. The result of this second process is written to this named pipe.

without process change:

 while ... do ... done inputfile #error while ... do ... done < inputfile #correct 

The same rules as when using a replacement:

 while ... do ... done <(cat foo) #error while ... do ... done < <(cat foo) #correct 

Alternative:

 cat foo >3 & while read line; do echo $line; done <3; 
+4
source

I can only suggest a workaround:

 theproc() { for((i=0;i<5;++i)) do echo $i; } while read line ; do echo $line ; done <<<"$(theproc)" 
+2
source

Source: https://habr.com/ru/post/1391475/


All Articles