LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (https://www.linuxquestions.org/questions/linux-general-1/)
-   -   unable to redirect command output into a file (https://www.linuxquestions.org/questions/linux-general-1/unable-to-redirect-command-output-into-a-file-4175499376/)

rohitchauhan 03-25-2014 05:01 AM

unable to redirect command output into a file
 
Hi guys,
I need a little help in scripting.

Code:

[root@base ~]# free -m
            total      used      free    shared    buffers    cached
Mem:          7766      6181      1585          0        200      1270
-/+ buffers/cache:      4710      3056
Swap:        5999        67      5932

I want this output in every 1 min repeatedly. I want to redirect value "3056" into a file.

Therefore, if I run the following command:
# free -m | grep buffers | tail -n 1 | awk '{print $4}' > test1
which is successful.

but when I run the command using "-s" option, it won't work.
# free -m -s 2 | grep buffers | tail -n 1 | awk '{print $4}' > test1


Can anybody tell me:
1. Why it is not working if I use '-s' switch ?
2. If it is not possible to use '-s' switch here, then is there any other way to run this command in every 2 seconds and get the require result into a file?

(If possible, I would prefer one liner script/command)

Thanks.

kirukan 03-25-2014 05:11 AM

Have a look on this thread
http://www.linuxquestions.org/questi...ommand-739669/

Ser Olmy 03-25-2014 05:16 AM

It doesn't work because the "-s 2" switch means "continue to write new statistics every 2 seconds", which means the output never ends, and this conflicts with two other commands through which you're piping the output.

tail -n 1 means "wait for end-of-file and output last line". Since free produces continuous output with the "-s 2" switch, tail will never see the end of the file, and hence produce no output.

There is a similar issue with the grep/awk combo; see kirukan's link for more information.

rohitchauhan 03-26-2014 01:12 AM

Thanks to both of you for quick and specific answers.
I get this thing running and working fine for me.
Code:

[root@base ~]# free -m -s 2 |  awk '/buffers\/cache/{print $4;fflush()}' > op &
[1] 13580
[root@base ~]#
[root@base ~]# kill -9 13580
[root@base ~]#
[root@base ~]# cat op
3030
3030
3030
3030
[1]+  Killed                  free -m -s 2 | awk '/buffers\/cache/{print $4;fflush()}' > op

But I cant understand the use of "fflush()" in the command.

Can you please help me in understanding this ?

Thank you !

kirukan 03-26-2014 01:31 AM

Does this manpage make sense?
http://manpages.courier-mta.org/htmlman3/fflush.3.html

rohitchauhan 03-27-2014 12:27 AM

Thank you very much.

Now i will mark this thread as solved.


All times are GMT -5. The time now is 02:31 PM.