Bash – Log to Screen and File Simultaneously

The Problem

In my bash script, I would like to print both the the standard output (typically the screen) and a file.

The Solution

Below is a simple script which demonstrate the solution.

#!/bin/sh

# whatis: Demo script that prints to both screen and a file

{
    echo Logging demo
    echo Output will go both the screen and logging.log
    # Other lines which might produce output here
    
} | tee logging.log

Discussion

Normally, the output from a bash script goes to the standard output, typically the screen. To redirect the output to both the standard output and a file, we employ the tee program. By surrounding the block of code with curly braces, we redirect the whole block, not just individual lines.

5 thoughts on “Bash – Log to Screen and File Simultaneously

  1. Pingback: Echo na tela e no log – scriptshell | Piqueti

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s