When running some tests, I need to run a series of commands. It would be extremely useful to me, and save me a lot of time, if there was a way to do all of these things:
- Run the command I need to run
- Redirect all the output from the command to a specified file
- Include the original command in the specified file
- Print the output from the original command in the terminal
People have suggested using tee to me which does a great job of printing to terminal as well as sending to a file but doesn't include the original command. What I'd like to end up with is a file where the first line is the command I ran, and then below that is the output from the command.
Someone suggested this:
echo "ls -l" | xargs -I{} bash -c "echo >> output.file; eval {} >> output.file"
But this doesn't either print the output in the terminal or include the original command in the file.
I'd appreciate any ideas.
That's
tee
you're searching for.prints the output of
ls -l
to stdout (i.e. the terminal) and saves it in the fileoutfile
at the same time. But: It doesn't write the command name neither to stdout nor to the file. To achieve that, justecho
the command name before running the command and pipe both outputs totee
:That's cumbersome to type, so why not define a function?
After that you can just run
to get the desired result. Put the function in your
~/.bashrc
to have it defined in every new terminal.If you want to be able to specify the output file as the first argument like in
instead make it:
If you don't want the output file to be overwritten but rather append to it, add the
-a
option totee
.You could make use of the
script
command which will make a typescript file of everything printed to your terminal. It creates a forked shells and will record everything until that shell is exited.Then if I
cat my_output
I get the same output:You can use the debugging function of the shell together with
tee
:( ... )
starts a sub-shell which allows you to “collect” the output streams of all commands executed within the sub-shell. It also contains the effect of theset
command below to this sub-shell.set -x
enables thex
shell option which prints all commands that the shell runs to the standard error stream before running them.2>&1
redirects stream 2 (standard error) to stream 1 (standard output).|
redirects the the standard output stream of the left command to the standard input stream of the right command.tee FILE
copies the standard input stream to the fileFILE
and to standard output.If your command sequence is already in a script file it would make more sense to run it like this: