Bash脚本-将stderr存储在变量中 [英] Bash script - store stderr in a variable

查看:100
本文介绍了Bash脚本-将stderr存储在变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本来备份数据库.我有以下一行:

I'm writing a script to backup a database. I have the following line:

mysqldump --user=$dbuser --password=$dbpswd  \
   --host=$host $mysqldb | gzip > $filename

我想将stderr分配给一个变量,以便它将向自己发送一封电子邮件,让我知道如果出现问题,会发生什么.我已经找到了将stderr重定向到stdout的解决方案,但是由于stdout已经(通过gzip)发送到了文件中,因此我无法做到这一点.如何将stderr分别存储在变量$ result中?

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 separately store stderr in a variable $result ?

推荐答案

尝试将stderr重定向到stdout并使用$()进行捕获.换句话说:

Try redirecting stderr to stdout and using $() to capture that. In other words:

VAR=$((your-command-including-redirect) 2>&1)

由于您的命令将stdout重定向到某处,因此它不应干扰stderr.也许有一种更简洁的编写方法,但是应该可以.

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,文件log包含out.

这篇关于Bash脚本-将stderr存储在变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆