Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux, write output to file, including the command

Tags:

linux

bash

How can I write into a file the output of a command but also include the command at the beginning of a file?

eg:

grep -nrs 'blah' . >/home/ca/out.txt

so that the file shows

grep -nrs 'blah' . >/home/ca/out.txt
./something.cpp:1329:    if(blah)

to leave a blank line between?

grep -nrs 'blah' . >/home/ca/out.txt

./something.cpp:1329:    if(blah)
....

Thank you

like image 785
thahgr Avatar asked Sep 12 '26 04:09

thahgr


2 Answers

You can store command line and result both in a file using bash -vc like this:

bash -vc "grep -nrs 'blah' ." >& /home/ca/out.txt
  • -v is for verbose mode in bash that outputs full command before executing it.
  • -c is for running a command from command line
  • >& is for redirecting both stdout and stderr

Another approach is store command line in an array:

arr=(grep -nrs 'blah' .)
{ printf "%q " "${arr[@]}"; echo; echo; "${arr[@]}"; } >& /home/ca/out.txt
like image 199
anubhava Avatar answered Sep 14 '26 23:09

anubhava


You can use logsave (usage) to log the output together with a timestamp and the command, e.g.:

logsave -a output.txt ls

Saves the output of the ls command into output.txt:

Log of ls 
Thu Jan 29 16:49:25 2015

[output of command]

Thu Jan 29 16:49:25 2015
----------------
like image 24
runDOSrun Avatar answered Sep 15 '26 00:09

runDOSrun