bash脚本 - 店标准错误变量 [英] Bash script - store stderr in variable
问题描述
我在写一个脚本来备份数据库。我有以下行:
I'm writing a script to backup a database. I have the following line:
mysqldump --user=$dbuser --password=$dbpswd \
--host=$host $mysqldb | gzip > $filename
我想标准错误分配给一个变量,因此,它会发送一封电子邮件给我,让我知道发生了什么,如果出现错误。我找到的解决方案,标准错误重定向到标准输出,但我不能这样做,因为标准输出已经被发送(通过gzip的)到一个文件中。我怎么能单独存储标准错误的变量$结果呢?
I want to assign the stderr to a variable, so that it will send an email to myself letting me know what happened if something goes wrong. I've found solutions to redirect stderr to stdout, but I can't do that as the stdout is already being sent (via gzip) to a file. How can I seperately store stderr in a variable $result ?
推荐答案
尝试重定向标准错误到标准输出,并使用 $()
来捕捉。换句话说:
Try redirecting stderr to stdout and using $()
to capture that. In other words:
VAR=$((your-command-including-redirect) 2>&1)
由于您的命令重定向标准输出的地方,它不应该有标准错误干涉。有可能是把它写一个更清洁的方式,但应该工作。
Since your command redirects stdout somewhere, it shouldn't interfere with stderr. There might be a cleaner way to write it, but that should work.
编辑:
这确实工作。我测试过它:
This really does work. I've tested it:
#!/bin/bash
BLAH=$((
(
echo out >&1
echo err >&2
) 1>log
) 2>&1)
echo "BLAH=$BLAH"
将打印 BLAH = ERR
,文件日志
包含退出
。
这篇关于bash脚本 - 店标准错误变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!