How to include the command in the output file?

51 views Asked by At

I have been reading quite a lot of information about stdin, stdout and stderr. I get the mechanism. But how do I include the command I type in, and the result to the output file?

Example

If I type in the following commands,

echo Hello! > abc.txt
cat abc.txt > finalOutput.txt

When I open finalOutput.txt I want to see,

cat abc.txt
Hello!

I have tried,

cat abc.txt 0> finalOutput.txt
cat abc.txt > finalOutput.txt 0>&1
Question

I know there are other methods such as script, logsave, bash, etc. But is there a SINGLE command (not too chunky) to record both INPUT and OUTPUT of a command, and write them into a file?

1

There are 1 answers

1
Zac On

Simplest Answer

You can use set -x in the script such that every line evaluated will be output. You can then run the script externally to log to a file like

# test
#!/bin/sh
set -x
echo "Hello World!"
$ ./test
+ echo Hello World!
Hello World!

You would then use this like: ./test > finalOutput.txt, perhaps from a wrapper/debug script?

More Complicated Solutions

  • I came up with exec &> >(tee finalOutput.txt), it's close to logging all output to a file from within the script, but there's a buffering problem that makes it hang. I'm not sure how to handle that here.