Reputation: 57
echo start commanda
output=$(commanda soemthing)
echo $output
echo start commandb
output=$(commandb something)
echo $output`
How do i do it in shell such that i keep:
echo start commanda
echo start commandb
in stdout, while keeping:
echo start commanda
echo $output
echo start commandb
echo $output
in a logfile?
Upvotes: 1
Views: 52
Reputation: 113924
When you want stdout to go to a file, use redirection. When you want it to go two places, use tee
:
echo start commanda | tee -a logfile
output=$(commanda soemthing)
echo $output >>logfile
echo start commandb | tee -a logfile
output=$(commandb something)
echo $output >>logfile
How it works:
>>logfile
is called redirection. It captures stdout and appends it to the file logfile
.
| tee -a logfile
captures the stdout of the previous command, appends a copy to logfile
and duplicates it again to stdout. If you want the file to be overwritten rather than appended to, then omit the -a
.
The following sends all output to logfile
. Any output line that starts with start
is also sent to stdout:
{
echo start commanda
output=$(commanda soemthing)
echo $output
echo start commandb
output=$(commandb something)
echo $output
} | tee -a logfile | grep '^start'
The braces, {...}
, group the statements together so that we only need redirect for the whole group. This reduces the number of times that the file logfile
is opened and closed. The disadvantage of this approach is that, if the output
starts with start
, it will also be sent to stdout.
Upvotes: 1