How to record the output of a bash script from terminal without suppressing the terminal output? [duplicate]

How to record the output of a bash script from terminal without suppressing the terminal output like $ ./bash-script.sh >> terminal.txt ? and I want to record the resulting output to text and keep it in the terminal as well.


 I want to record the resulting output to text and keep it in the terminal as well

What you want is tee command. It allows echoing text to stdout and to a file. For example:

$ ls -l /etc/passwd | tee output_file.txt                                      
-rw-r--r-- 1 root root 2989 6月  17 20:45 /etc/passwd
$ cat output_file.txt                                                          
-rw-r--r-- 1 root root 2989 6月  17 20:45 /etc/passwd

The tee command is good for capturing output from non-interactive commands. For interactive terminal applications, the package bsdutils gives you script command that allows recording the output to terminal while allowing you to interact with the application like usual. The difference between the two is that script will give the application the impression of running under a terminal and this might make a difference how the utility behaves. Also, script captures standard error without requiring to do additional redirects in the shell command line.

You can use it like this:

$ script -c script.sh output.log

(where script.sh is assumed to be found in $PATH) or

$ script -c "script.sh arguments" output.log

Running it without -c "${command}" option will run shell and allows saving the shell session to a file.

As bsdutils is an "essential" package and its priority is "required" you might have it already installed. Just try issuing command script (followed by exit to stop recording to the default file typescript).

In general I personally usually prefer script over tee though many interactive terminal applications seem to run just fine when output is piped to tee.


You can use tee

For example,

./script.sh | tee logfile

will cause the output of the script to be saved in logfile as well as shown in the terminal output.

If you want to store all outputs of subsequent script executions, you may want to append to that file. In that case, you'd use tee -a instead

./script.sh | tee -a logfile
./script2.sh | tee -a logfile