Search code examples
bashshellstdoutstderrtee

How to print shell script stdout/stderr to file/s and console


In the bash script I use the following syntax I order to print everything from the script to the files - $file and $sec_file

we are running the script on our Linux rhel server - version 7.8

exec > >(tee -a "$file" >>"$sec_file") 2>&1

so after bash script completed , we get on both files the content of stdout/stderr of every line in the bash script

now we want additionally to print to the console the stdout/stderr and not only to the files

I will appreciate of any suggestion

Example of the script:

# more  /tmp/script.bash

#!/bin/bash

file=/tmp/file.txt
sec_file=/tmp/sec_file.txt

exec > >(tee -a "$file" >>"$sec_file") 2>&1

echo "hello world , we are very happy to stay here "

Example how to run the script:

/tmp/script.bash

<--  no output from the script -->

# more /tmp/file.txt
hello world , we are very happy to stay here
# more /tmp/sec_file.txt
hello world , we are very happy to stay here

example of expected output that should be as the following

/tmp/script.bash
hello world , we are very happy to stay here

and

# more /tmp/file.txt
hello world , we are very happy to stay here
# more /tmp/sec_file.txt
hello world , we are very happy to stay here

Solution

  • I think, the easiest is to just add multiple files as arguments to the tee like this:

    % python3 -c 'import sys; print("to stdout"); print("to stderr", file=sys.stderr)' 2>&1 | tee -a /tmp/file.txt /tmp/file_sec.txt
    to stdout
    to stderr
    % cat /tmp/file.txt 
    to stdout
    to stderr
    % cat /tmp/file_sec.txt 
    to stdout
    to stderr
    

    Your script would look like this then:

    #!/bin/bash
    
    file=/tmp/file.txt
    sec_file=/tmp/sec_file.txt
    
    exec > >(tee -a "$file" "$sec_file") 2>&1
    
    echo "hello world , we are very happy to stay here "