0

我试图在 Linux 上的 shell 脚本中捕获失败命令的错误代码。在这种情况下,我的 ffprobe 命令:

#!/bin/sh
    videoduration=$(ffprobe -loglevel error -show_format myfile.avi | grep duration | cut -d= -f2)
    if [ $? -ne 0 ]; then
       echo "ERROR"
       exit 1
    fi
echo $videoduration

如果我更改该命令以提供虚假文件名:

#!/bin/sh
    videoduration=$(ffprobe -loglevel error -show_format myfile.av | grep duration | cut -d= -f2)
    if [ $? -ne 0 ]; then
       echo "ERROR"
       exit 1
    fi
echo $videoduration

错误代码在这里没用,因为从技术上讲,状态代码仍然是 0。代码仍然会有一个成功的grepcut。如果 ffprobe 命令失败,如何将此命令保存在单个变量中但因错误退出?

编辑:如果有的话,我更喜欢非 shell 特定的答案。建议的副本也涵盖了类似的情况,但这里唯一可能的选择是创建一个临时文件,如下所示:

f=`mktemp`
(ffprobe ...; echo $?>$f) | ...
e=`cat $f` #error in variable e
rm $f

似乎是创建临时文件的黑客?如果这是唯一的选择,我将如何将其存储在变量中?

4

1 回答 1

0

问题是即使ffprobe命令失败,cut也不会返回零退出代码。管道的退出状态是最后一个命令的退出状态,除非您的 shell 有办法更改此行为以返回第一个命令的退出状态失败。您可以使用set -o pipefailin bash/执行此操作ksh

$ false | cut -d= -f2; echo $?
0
$ set -o pipefail 
$ false | cut -d= -f2; echo $?
1
于 2013-04-04T07:15:26.923 回答