Take the 2-minute tour ×
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 haven't had much luck finding an answer to my problem, but maybe I'm not asking for it correctly.

I have a process I startup like the following:

nohup ping 127.0.0.1 > log.txt >2>&1 &

Pretty simple command, send all the stdout to log.txt. Only problem is that the command I'm running sends data every nth second to log.txt. I'd like to output just one line to my log.txt file instead of appending it and running the risk of filling my drive up.

Is there a way to just output one line to log.txt that continuously gets overwritten?

share|improve this question
    
This would require a seek(0) before every write, or closing and reopening the file for each write. –  jordanm Nov 13 '12 at 16:38
3  
Why have a file in the first place if you are just going to continuously overwrite it? Just run it in a screen or tmux session. The other approach if you really want a file, is to pipe the output to a simple script that does the overwriting for you (read n lines, overwrite file, ad infinitum). –  jw013 Nov 13 '12 at 16:44
    
Writing to a file is not mandatory, I just need to pickup the latest output from the command in a webpage (some shell_exec call in php). Is it possible to just redirect the output to something that I can call and see what it's doing? –  eproms Nov 13 '12 at 16:51

2 Answers 2

up vote 6 down vote accepted

Here is a quick and dirty solution to only keep the last line of output in the log file:

ping localhost | 
  while IFS= read -r line; do 
    printf '%s\n' "$line" > log.txt; 
  done

Beware that you now probably have all kinds of race conditions when trying to access the file for reading. "Locking" the file from mutual access might help. For more information about locking this question on stackoverflow might be a good start: How do I synchronize (lock/unlock) access to a file in bash from multiple scripts?

share|improve this answer

Try this script, it works for me:

% nohup ping 127.0.0.1 > log.txt >&1&

Check if the process is running by typing:

% ps ax | grep ping

If the process is running:

% tail -f log.txt

If it continues pinging, your script is working properly.

share|improve this answer

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.