I have a bash loop like this:
for f in *.fastq; do
echo $f
main command
done
I want to print anything that gets printed in my terminal (including file names and error messages) to a text file. How can I do this? Thanks
If you do not want to keep the stdout, stderr being displayed on your screen you can just after your loop redirect both stdout and stderr to a file in overwrite mode or append mode using respectively:
for f in *.fastq; do
echo $f
main command
done > file.out 2>&1
or
for f in *.fastq; do
echo $f
main command
done >> file.out 2>&1
If you want to have at the same time both stderr, stdout displayed to your screen and saved to a file use:
for f in *.fastq; do
echo $f
main command
done |& tee file.out
or
for f in *.fastq; do
echo $f
main command
done |& tee -a file.out
where tee -a runs tee in append mode and |& is a shorthand for 2>&1 |
READINGS: https://www.gnu.org/software/bash/manual/bash.html#Redirections https://unix.stackexchange.com/questions/24337/piping-stderr-vs-stdout
> >(tee somefilename) 2>&1immediately after thedonewill suffice. If you really mean terminal output, as in inclusive of content written directly to/dev/tty(which is often done explicitly to bypass logging or interception for security reasons), then you need to use a tool such asscript,screen(with its logging options), etc.