Pra*_* BJ 0 shell-script echo tee
附加一个包含tee命令和日志文件名的变量,没有得到预期的结果,因为echo正在打印变量内容。
以下是文件内容、实际输出和预期结果。
shell脚本内容:
#!/bin/bash
log="2>&1 | tee -a report.txt"
echo ""
echo '***************-:START OF THE REPORT:-***********' $log
Run Code Online (Sandbox Code Playgroud)
运行脚本后。
console op:
***************-:START OF THE REPORT:-*********** 2>&1 | tee -a report.txt
Run Code Online (Sandbox Code Playgroud)
预期的-
console op:
***************-:START OF THE REPORT:-***********
report.txt file content:
***************-:START OF THE REPORT:-***********
Run Code Online (Sandbox Code Playgroud)
另请注意,变量$log应包含tee命令和文件名,因为我不想tee在每个 echo 命令的末尾对命令进行硬编码。
我假设您想使用这种不寻常的方式来标记实际管道并添加tee到日志消息的末尾,因为您不希望每个echo?
好吧,你也可以这样做:
logfile='report.txt'
log () {
if [ -z "$1" ]; then
cat
else
printf '%s\n' "$@"
fi | tee -a "$logfile"
}
log "some message"
log "some other message"
log "multi" "line" "output"
{
cat <<LETTER
Dear Sir,
It has come to my attention, that a whole slew of things may be
collected and sent to the same destination, just by using a single
pipe. Just use { ... } | destination
Sincerely, $LOGNAME
LETTER
cat <<THE_PS
PS.
Here's the output of "ls -l":
THE_PS
ls -l
echo "LOL"
} | log
Run Code Online (Sandbox Code Playgroud)
也就是说,将笨拙的tee命令包装在一个简单的 shell 函数中,该函数的名称易于键入,并将输出通过管道传递给它。
在此示例中,该log函数用于printf输出在其命令行上给出的数据,或者如果这些没有命令行参数,则切换到从标准输入读取。
你甚至可以使用
./your_original_script_without_special_logging 2>&1 | log
Run Code Online (Sandbox Code Playgroud)