7

Hi I want to save both output of a command and the command that has been run to create the output into the same single file. I understand either of

*some_command* > file.txt   
*some_command* | tee file.txt

can be done but either case the some_command doesn't get saved into the file but only the output of it gets saved. Is there a way to do so ?

  • You want the command printed for logging reasons? – pLumo Jul 31 '19 at 07:09
  • You are probably looking for script which will create a new session and store everything on the terminal in a file called "typescript" until you leave the session. – Panki Jul 31 '19 at 07:09
  • @pLumo yes I am trying to log. – Raghavendra Sugeeth Jul 31 '19 at 07:15
  • 1
    Do you want the command as entered on the command line (e.g. ls -l "$dir"/*.txt) or the resulting command that was run, after all expansions (e.g. ls -l ./foo/file1.txt ./foo/file2.txt)? – ilkkachu Jul 31 '19 at 07:23

3 Answers3

1

You can store the command in an array, print and run it:

# Define command
mycmd=(some_command -o "some option")

# Print command
echo "${mycmd[@]}"

# Run command
"${mycmd[@]}" 

See also.

Note, this will strip the quotes when printing the command.


Put it in a function:

lognrun(){ echo "$@"; "$@"; }
lognrun some_command -o "some_option" > logfile
pLumo
  • 22,565
1

Use a subshell with set -x:

$ ( set -x; printf '%s\n' a b "c d"; ) 2>&1 | tee logfile
+ printf '%s\n' a b 'c d'
a
b
c d
pLumo
  • 22,565
  • Note that the trace output generated by set -x is not actually showing the commands as they were given to the shell. – Kusalananda Jul 31 '19 at 09:07
1

How about using the 'script'-command?

$ script logfile
$ somecommand
lots of command output...

This will log everything you do on the shell to logfile. Stop with Ctrl+D.

If you only need it for one command, you can use the '-c'-option:

-c, --command command
    Run the command rather than an interactive shell.
    This makes it easy for a script to capture the output of a program
    that behaves differently when its stdout is not a tty.
markgraf
  • 2,860
  • script seems fine but it also saves all other information like time of script etc. I don't think I need them. – Raghavendra Sugeeth Jul 31 '19 at 09:51
  • 1
    Ah, I forgot about that... Some postprocessing then:

    script -c "ls -lvhF" temp/logfile ; sed '1d' temp/logfile | head -n -2

    to get rid of the unneeded extras.

    – markgraf Jul 31 '19 at 10:53