Skip to main content

How to use tee command with echo as per below requirement? [Resolved]

Appending a variable which contains the tee command and log file name, not getting the expected result, since echo is printing the variable content.

Below is the file content, actual output and expected result.

Content of shell script:

#!/bin/bash

log="2>&1 | tee -a report.txt"

echo ""
echo '***************-:START OF THE REPORT:-***********' $log

After running the script.

console op:
***************-:START OF THE REPORT:-*********** 2>&1 | tee -a report.txt

expected-

console op:
***************-:START OF THE REPORT:-***********

report.txt file content:
***************-:START OF THE REPORT:-***********

Also note that ,variable $log should contain both the tee command and file name, since I don't want to hard code the tee command at end of each echo command.


Question Credit: Prashant BJ
Question Reference
Asked September 19, 2019
Posted Under: Unix Linux
14 views
3 Answers

You should actually use a function masking the command echo for this:

echo ()
{
    builtin echo "$@" | tee -a report.txt
}

Then you can do:

echo ""
echo '***************-:START OF THE REPORT:-***********'

Without having to hardcode tee or anything else at the end of echo commands.


credit: muru
Answered September 19, 2019
Your Answer