Tell me more ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to output a file's contents while they change, for example if I have the file foobar and I do:

magic_command foobar

The current terminal should display the file's contents and wait until, I don't know, I press ^C.

Then if from another terminal I do:

echo asdf >> foobar

The first terminal should display the newly added line in addition to the original file contents (of course, given that I didn't press ^C).

I'll mark this as homework since I want to explore and learn linux, but it's not homework, it's just a curiosity of mine.

share|improve this question
possible duplicate of Reading from a continuously changing logfile – Gilles Aug 16 '12 at 23:15

2 Answers

up vote 12 down vote accepted

You can use tail command with -f :

tail -f /var/log/syslog 

It's good solution for real time show.

share|improve this answer
Yep, it worked! At first I thought about something with pipes, but I had to come up with a way to keep the reading end open forever... – Paul Aug 16 '12 at 14:40
you can write a script and redirect your output to your script. – Mohsen Pahlevanzadeh Aug 16 '12 at 20:11

When I need to detect file changes and do something other than what tail -f filename does, I've used inotifywait in a script to detect the change and act upon it. An example of use is shown below. See man inotifywait for other event names and switches. You may need to install the inotify-tools package, for example via sudo apt-get install inotify-tools.

Here's the example script, called exec-on-change:

 #!/bin/sh

# Detect when file named by param $1 changes.
# When it changes, do command specified by other params.

F=$1
shift
P="$*"

# Result of inotifywait is put in S so it doesn't echo
while  S=$(inotifywait -eMODIFY $F 2>/dev/null)
do
  # Remove printf if timestamps not wanted 
  printf "At %s: \n" "$(date)"
  $P
done

In two consoles I entered commands as follows (where A> means entry in console A, and B> means entry in console B.)

A> rm t; touch t
B> ./exec-on-change t wc t
A> date >>t
A> date -R >>t
A> date -Ru >>t
A> cat t; rm t

The following output from cat t appeared in console A:

Thu Aug 16 11:57:01 MDT 2012
Thu, 16 Aug 2012 11:57:04 -0600
Thu, 16 Aug 2012 17:57:07 +0000

The following output from exec-on-change appeared in console B:

At Thu Aug 16 11:57:01 MDT 2012: 
 1  6 29 t
At Thu Aug 16 11:57:04 MDT 2012: 
 2 12 61 t
At Thu Aug 16 11:57:07 MDT 2012: 
 3 18 93 t

The exec-on-change script terminated when I rm'd t.

share|improve this answer
I'll take a look on inotifywait tomorrow, thank you! – Paul Aug 16 '12 at 19:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.