Why redirection to a while loop doesn't print the messages?

Here is a shell code used to track changes in a file and output the content to the terminal:

while read LINE
do echo $LINE
done < `tail -f /var/log/messages`

It doesn't work, why?

2

2 Answers

There is no need for a while loop. You try to do two times the same. Also the file /var/log/messages is not present in ubuntu anymore.

Just use:

tail -f /var/log/syslog

to track new content that is added at the end of the text file. If something new is written to the end of /var/log/syslog it is printed to your terminal.

Edit: Why the command in the question doesn't work:

First, of course, /var/log/messages does not exist. But if it would exist, the command between backticks is executed and replaced by its output (minus the trailing newline characters). So the output of tail -f ... would be taken as filename for the input redirection <. What you probably want would look as follows (the the <(...) redirection):

while read LINE; do echo $LINE
done < <(tail -f /var/log/messages)

The <(...) redirection creates a named pipe, where on one end the command tail -f writes to. On the other end the while loop reads the contents line by line. A named pipe behaves likely to a regular file. It is just a connection piece between two commands. BTW, the | does exactly the same, but those pipe are not named, they are the default channels: 0 -> stdin, 1 -> stdout and 2 -> stderr.

From the bash manpage:

 Process substitution is supported on systems that support named pipes (FIFOs) or the /dev/fd method of naming open files. It takes the form of <(list) or >(list). 
10

The usual portable way of doing this is:

tail -f /var/log/messages | while read LINE
do echo $LINE
done

@chaos's answer is using process substitution syntax which is only found in advanced shells such as zsh and bash. You should not rely on their features if you ever need to run your script on a different computer.

Of course, I assume that you want to put something more complex than echo $LINE into the loop.

5

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like