Capture all the output of a script to a file (from the script itself)
You can always invoke script
inside a script to log everything.
As to print and log everything at the same time in a bash script to log.txt
:
#!/bin/bash
if [ -z "$SCRIPT" ]
then
/usr/bin/script log.txt /bin/bash -c "$0 $*"
exit 0
fi
echo teste
Seeing the log log.txt
:
$ ./a.sh
Script started, output file is log.txt
teste
Script done, output file is log.txt
$ cat log.txt
Script started on Fri Feb 16 17:57:26 2018
command: /bin/bash -c ./a.sh
teste
Script done on Fri Feb 16 17:57:26 2018
You want to use tee.
Ex:
echo "Hello World" | tee out.txt
This creates a file out.txt with the output from the command and prints it to the screen. Use "tee -a filename" if you want to append to the file.
echo "Hello" | tee -a out.txt
echo "World" | tee -a out.txt
out.txt will have two lines Hello and World (without -a it would only have world)
If you want to save the entire script and output the entire script:
./script.sh | tee output.txt