In a bash script, I'd like to:
- output every logs into a file (
loglowlevel.txt
), - but make only few of them visible in terminal (high-level),
- I have, say, 20 high-level logs and 60 low-level logs. Thus I'd like to keep low-level logs "redirection-command" free, and have the redirection stuff to high-level logs only.
Take 1
I wrote a basic script that redirects stdout
and sterr
to FD 3. loglowlevel.txt
is correctly populated. But I am stuck in specifying the option for the high-level logs.
#!/bin/bash -
# create fd 3
exec 3<> loglowlevel.txt
# redirect stdout and stderr to fd 3
exec 1>&3
exec 2>&3
# high-level logs' redirection below is wrong
echo "high-level comment" 3>&1
# low-level logs should remain redirection-free, as below
echo "low-level comment"
ls notafile
# close fd 3
3>&-
Here is what it does:
$ redirect.sh
$ cat loglowlevel.txt
low-level comment
ls: cannot access notafile: No such file or directory
I expected high-level comment
to be printed on terminal as well.
Take 2
Second script, different strategy:
#!/bin/bash -
function echolowlevel() {
echo $1 &>loglowlevel.txt
}
function echohighlevel() {
echo $1 |& tee loglowlevel.txt
}
echohighlevel "high-level comment 1"
echolowlevel "low-level comment 1"
echohighlevel "high-level comment 2"
ls notafile
Here is what it does:
$ redirect.sh
high-level comment 1
high-level comment 2
ls: cannot access notafile: No such file or directory
$ cat loglowlevel.txt
high-level comment 2
Two problems here:
- error message from
ls
is printed in terminal, whereas I need it only inloglowlevel.txt
. high-level comment 1
has been eaten inloglowlevel.txt
.
Question
I prefer the idea behind Take 1. But how can I make high-level comment
be output to stdout while keeping the two exec
commands?
tee(1)
?-a
option in tee.