Differences between revisions 18 and 19
Revision 18 as of 2015-04-08 22:51:14
Size: 2005
Editor: geirha
Comment: include example with `read -u` and `{var}<file`
Revision 19 as of 2015-04-08 22:52:10
Size: 2085
Editor: geirha
Comment: syntax highlighting
Deletions are marked like this. Additions are marked like this.
Line 5: Line 5:
{{{ {{{#!highlight bash
Line 12: Line 12:
{{{ {{{#!highlight bash
Line 22: Line 22:
{{{ {{{#!highlight bash
Line 31: Line 31:
{{{ {{{#!highlight bash
Line 39: Line 39:
{{{ {{{#!highlight bash

I'm reading a file line by line and running ssh or ffmpeg, only the first line gets processed!

When reading a file line by line, if a command inside the loop also reads stdin, it can exhaust the input file. For example:

   1 # Non-working example
   2 while IFS= read -r file; do
   3   ffmpeg -i "$file" -vcodec libxvid -acodec libfaac -ar 32000 "${file%.avi}".mkv
   4 done < <(find . -name '*.avi')

   1 # Non-working example
   2 while read host; do
   3   ssh "$host" some command
   4 done <hostslist

What's happening here? Let's take the first example. read reads a line from standard input (FD 0), puts it in the file parameter, and then ffmpeg is executed. Like any program you execute from BASH, ffmpeg inherits standard input, which for some reason it reads. I don't know why. But in any case, when ffmpeg reads stdin, it sucks up all the input from the find command, starving the loop.

Here's one way to make it work:

   1 while IFS= read -r file; do
   2   ffmpeg -i "$file" -vcodec libxvid -acodec libfaac -ar 32000 "${file%.avi}".mkv </dev/null
   3 done < <(find . -name '*.avi')

Notice the redirection on the ffmpeg line: </dev/null. The ssh example can be fixed the same way, or with the -n switch (at least with OpenSSH).

Sometimes with large loops it might be difficult to work out what's reading from stdin, or a program might change its behaviour when you add </dev/null to it. In this case you can make read use a different FileDescriptor that a random program is less likely to read from:

   1 while read -r line <&3; do
   2   ...
   3 done 3<file

In bash, the read builtin can also be told to read directly from an fd (-u fd) without redirection, and since bash 4.1, an available fd can be assigned ({var}<file) instead of hard coding a file descriptor.

   1 # bash 4.1+
   2 while read -r -u "$fd" line; do
   3   ...
   4 done {fd}<file

BashFAQ/089 (last edited 2024-04-13 21:56:35 by Reg)