3

All the commands I've seen so far look like command > file or command >> file, which output the result to the designated file. For instance, when I type openssl version > lab4.txt, all I see in the text file is OpenSSL 1.0.1e-fips 11 Feb 2013.

What if I want to output both the command I typed and the result that was returned one below the other like this?

linux2[20]% openssl version
OpenSSL 1.0.1e-fips 11 Feb 2013

Thanks for helping

  • from bash set -x;exec | tee file might be handy. – hildred Apr 20 '15 at 10:08
6

The redirection operator command > file will redirect the STDOUT of a command, or STDERR of a command if used like command 2> file or both if used like &> in bash or in any shell by portable command > file 2>&1 way. I am not aware of any direct method using redirection that can achieve what you need.

Although it is possible using the script program. It will basically save everything printed on the terminal in that script session.

From man script:

script makes a typescript of everything printed on your terminal. 
It is useful for students who need a hardcopy record of an 
interactive session as proof of an assignment, as the typescript file 
can be printed out later with lpr(1).

You can start a script session by just typing script in the terminal, all the subsequent commands and their outputs will all be saved in a file named typescript in the current directory. You can save the result to a different file too by just starting script like:

script output.txt

To logout of the screen session (stop saving the contents), just type exit.

Here is an example:

$ script output.txt
Script started, file is output.txt

$ ls
output.txt  testfile.txt  foo.txt

$ exit
exit
Script done, file is output.txt

Now if i read the file:

$ cat output.txt

Script started on Mon 20 Apr 2015 08:00:14 AM BDT
$ ls
output.txt  testfile.txt  foo.txt
$ exit
exit

Script done on Mon 20 Apr 2015 08:00:21 AM BDT

script also has many options e.g. running quietly -q (--quiet) without showing/saving program messages, it can also run a specific command -c (--command) rather than a session, it also has many other options. Check man script to get more idea.

  • 1
    Good to know. It is useful for making tutorials and related stuff. – rpax Apr 20 '15 at 5:36
  • @rpax: Yes, it is :) – heemayl Apr 20 '15 at 17:33
1

You would need to create a script with the following:
echo 'command -params/r' > file.lst
command -params >> file.lst

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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