Tom Tom -4 years ago 101
Bash Question

Shell, redirect all output to a file but still print echo

I have multiple vagrant provisions (shell scripts), and I would like to redirect all command output to a file while keeping the

echo
output in stdout.

Currently I redirect all output by doing

exec &>> provision.log


At the beginning of each provision

Which works great, but console is empty. So I would like to redirect everything but the echo commands to a file.

If there would be a possibility of redirecting all output (including echo) to a file and keeping only echo in stdout that would be the best.

Result should look like:

Console

Starting provision "master"
Updating packages...
Installing MySQL...
ERROR! check provision.log for details


provision.log

Starting provision "master"
Updating packages...
...
(output from apt-get)
...
Installing MySQL...
...
(output from apt-get install mysql-server-5.5)
...
ERROR! check provision.log for details


I do realize I could attach output redirect to every command but that is quite messy

Answer Source

You can take this approach of duplicating stdout file descriptor and using a custom echo function redirecting to duplicate file descriptor.

#!/bin/bash

# open fd=3 redirecting to 1 (stdout)
exec 3>&1

# function echo to show echo output on terminal
echo() {
   # call actual echo command and redirect output to fd=3 and log file
   command echo "$@"
   command echo "$@" >&3
}

# redirect stdout to a log file    
exec >>logfile

printf "%s\n" "going to file"
date
echo "on stdout"
pwd

# close fd=3
exec 3>&-
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download