Bash 脚本 - 将 stderr 存储在变量中 [英] Bash script - store stderr in a 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
我想将 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屋!