2

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

3
  • 4
    Maybe you want script(1) ? Commented Jan 29, 2015 at 15:30
  • all are right answers, thank you very much, I will just choose the one that suits me best Commented Jan 29, 2015 at 15:59
  • I'm glad @BasileStarynkevitch mentioned script - I love that command, but haven't used it for years; and if you don't remember the name, hard to do an apropos to find it. Commented Jul 2, 2020 at 19:17

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Inserting a newline after command isn't easy with this approach. One needs to store whole command line an array and then insert newlines (see edit)
4

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
----------------

Comments

3

If you use it in a bash-script you can first write and echo line and then add the output to the file:

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

Comments

3

Use script command to save both command and output in same file, as follows

script -a mycommands.txt

Once the section to be recorded is complete, type exit in terminal to exit the program.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.