在 bash 脚本中,我想:
- 将每个日志输出到一个文件中(
loglowlevel.txt
), - 但在终端(高级)中只使它们中的少数可见,
- 比如说,我有 20 个高级日志和 60 个低级日志。因此,我想保持低级日志“重定向命令”免费,并且只将重定向内容重定向到高级日志。
拿 1
stdout
我写了一个重定向到sterr
FD的基本脚本3.loglowlevel.txt
被正确填充。但我坚持为高级日志指定选项。
#!/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>&-
这是它的作用:
$ redirect.sh
$ cat loglowlevel.txt
low-level comment
ls: cannot access notafile: No such file or directory
我希望high-level comment
也能在终端上打印。
拿 2
第二个脚本,不同的策略:
#!/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
这是它的作用:
$ 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
这里有两个问题:
- 来自的错误消息
ls
打印在终端中,而我只需要在loglowlevel.txt
. high-level comment 1
已经被吃掉了loglowlevel.txt
。
问题
我更喜欢Take 1背后的想法。但是如何在保留这两个命令high-level comment
的同时将其输出到标准输出?exec