如何将stdout和/或stderr重定向到在变量中指定的路径?注意:我不想覆盖变量本身,我想使std [xxx]写入变量中指定的文件。
例如,一个简单的脚本,如果scp
命令失败,则将失败消息输出到指定的日志文件,而不是将失败消息打印到stderr
或stdout
(我不确定失败时向哪个输出)。日志文件的路径存储在$LOG
变量中:
LOG=/path/to/file.log
scp file1 host@remote
# do 'whatever' if scp command succeeds:
if [ $? = 0 ];
then
whatever
else
# else log both stdout/stderr to ${LOG} file
&>"${LOG}"
# DEBUG - print contents of ${LOG} var for testing purposes
printf "${LOG}"
该脚本的结果未在/path/to/file.log
文件中显示任何内容,而仅显示/path/to/file.log
为stdout
。因此,好像没有写入任何内容&>
。
我已经确认我的特定scp
命令有效,所以我知道这不是潜在的问题。
还是这是处理自定义日志文件的最合适方法?是否有比配置变量中日志文件的路径更好的配置自己的日志系统的方法?
看起来您正在尝试在运行命令后记录输出,这是不可能的。
如果要scp
无条件记录命令的输出,则只需要在命令本身所在的行中包括重定向操作符即可,即:
&>"${LOG}" scp file1 host@remote
如果只想在命令失败时保存日志输出(您似乎正在尝试在代码中执行此操作),那么将输出重定向到一个临时文件,然后将该文件移到所需位置该怎么办?它可能看起来像这样:
#!/bin/bash
# Set path the real log file location
LOG=/path/to/file.log
# Create a temporary file to capture standard output and standard error
TEMPLOG="$(mktemp)"
# Run command and redirect output to temporary logfile
2>"${TEMPLOG}" scp file1 host@remote
# do 'whatever' if scp command succeeds:
if [ $? = 0 ];
then
echo 'Command successful!'
# else log both stdout/stderr to ${LOG} file
else
# Move the log file from the temporary location to the desired location
mv "${TEMPLOG}" "${LOG}"
# DEBUG - print contents of ${LOG} var for testing purposes
printf "${LOG}"
fi
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句