bash 每次运行 script.sh 并将输出保存到文件时,如何从我的 script.sh 中记录错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28193220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i log error from my script.sh every time I run the script.sh and save output to a file?
提问by Bruno Alves
How can I save the error output when running my script to a file? I have my code bellow, but the code does not track error and save the error to test.log14. Can somebody give me a hint on what could be wrong in my code...
将脚本运行到文件时如何保存错误输出?我有下面的代码,但代码没有跟踪错误并将错误保存到 test.log14。有人可以给我一个关于我的代码中可能有什么问题的提示......
LOGFILE=/usr/local/etc/backups/test14.log
"$(date "+%m%d%Y %T") : Starting work" >> $LOGFILE 2>&1
回答by Aaron Digulla
Use this code:
使用此代码:
#!/bin/bash
LOGFILE=/usr/local/etc/backups/test14.log
(
echo "$(date "+%m%d%Y %T") : Starting work"
... more commands ...
echo error 1>&2 # test stderr
echo "$(date "+%m%d%Y %T") : Done"
) >& $LOGFILE
The ()
makes BASH execute most of the script in a subshell. All output of the subshell (stderr and stdout) is redirected to the logfile.
这()
使得 BASH 在子 shell 中执行大部分脚本。子shell(stderr 和stdout)的所有输出都被重定向到日志文件。
回答by Dale_Reagan
Send the error output of the command instead of appending 'error output from append' -if that makes sense. I typically use functions for this type of process (similar to above.)
发送命令的错误输出,而不是附加“来自 append 的错误输出”——如果这有意义的话。我通常为这种类型的过程使用函数(类似于上面的)。
Try this:
尝试这个:
2>&1 >> $LOGFILE
instead of
代替
>> $LOGFILE 2>&1
###
function run_my_stuff {
echo "$(date "+%m%d%Y %T") : Starting work"
... more commands ...
echo "$(date "+%m%d%Y %T") : Done"
}
## call function and append to log
run_my_stuff 2>&1 >> ${LOGFILE} # OR
run_my_stuff 2>&1 | tee -a ${LOGFILE} # watch the log
回答by Ljm Dullaart
There are normally 2 outputs that you see on your screen when you execute a command:
执行命令时,通常会在屏幕上看到 2 个输出:
- STDOUT
- STDERR
- 标准输出
- STDERR
You can redirect them independently per command.
您可以根据命令独立重定向它们。
For example:
例如:
ls >out 2>err
will give you two files; out
will contain the output from ls
and err
will be empty.
会给你两个文件;out
将包含来自的输出ls
并且err
将为空。
ls /nonexisting 1>out 2>err
will give you an empty out
file and err
will contain
会给你一个空out
文件,err
并将包含
"ls: cannot access /nonexisting: No such file or directory"
“ls:无法访问/不存在:没有这样的文件或目录”
The 2>&1
redirects 2 (STDERR) to 1 (STDOUT)
所述2>&1
重定向2(STDERR)至1(STDOUT)
Your echo
does not have any errors, therefore there is no output on the STDERR.
您echo
没有任何错误,因此 STDERR 上没有输出。
So your code would probably need to be something like this:
所以你的代码可能需要是这样的:
echo "$(date "+%m%d%Y %T") : Starting work"
work_command > work_output 2>> $LOGFILE