bash - 数据库转储 | gzip-$?总是设置为 0

标签 bash

我在一个循环中转储数据库,如果我尝试转储一个不存在的数据库,我会得到 stderr mysqldump:出现错误:1049:选择数据库时出现未知数据库"is" 正如我所料,但是尽管出现错误 $? 始终返回 0。

我的代码如下:

for database in ${databases[@]}; do
    $dumpcmd $database | gzip > "$backupdir/$database.gz"
    result=$?
    echo "dumped database: $database ($result)"
done

我想从 mysqldump 中检测到一个错误并将其打印到屏幕上 - 我有一种预感,这与 gzip 的管道有关,但是作为一个试图学习 bash 的 C# 开发人员,我被卡住了!

最佳答案

您想检查 PIPESTATUS 中的内容:

   PIPESTATUS
          An  array  variable (see Arrays below) containing a list of exit
          status values from the processes in  the  most-recently-executed
          foreground pipeline (which may contain only a single command).

因此,请尝试使用 result=${PIPESTATUS[0]} 而不是 result=$?

关于bash - 数据库转储 | gzip-$?总是设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15953710/

相关文章:

bash - 如何在不执行的情况下编辑当前的 shell 命令?

bash - 在后台使用 HERE_DOC 方法运行脚本

python - 将 bash 脚本中的环境变量分配给 Python 中的当前 session

linux - 通过 ssh 连接并重试的 Shell 脚本

regex - grep 仅在两个字符串之间的区域

linux - Linux 中的电子邮件目录列表

linux - 脚本中 ps aux 和 `ps aux` 之间的不同结果

mysql - AWS Ubuntu 14.04 上的无人值守 MySQL 安装

linux - 在 bash 脚本中打开 pdf 文件的命令

bash - Redis-cli && bash 查找具有空值的键