0

I'm trying to catch the error code of a failed command in my shell script on Linux. In this case my ffprobe command:

#!/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

If I change that command to give a bogus file name:

#!/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

The error code is useless here because technically the status code is still 0. The code will still have a successful grep and cut. How can I keep this command in a single variable but exit with error if ffprobe command fails?

EDIT: I'd prefer a non shell specific answer if there is one. Also the proposed duplicate covers a similar case but the only potential option here is to create a temp file like so:

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

Seems like a hack creating a temp file? If this is the only option how would I store this in a variable?

Tom
  • 2,604
  • 11
  • 57
  • 96
  • I don't think so. I'd prefer a non shell specific answer. I'll edit accordingly. – Tom Apr 04 '13 at 03:40

1 Answers1

0

The problem is that even though the ffprobe command fails, the cut does not and returns a zero exitcode. The exit status of a pipe is the exit status of the last command, unless your shell has means to change this behaviour to return the exit status of the first command to fail. You can do this with set -o pipefail in bash/ksh:

$ false | cut -d= -f2; echo $?
0
$ set -o pipefail 
$ false | cut -d= -f2; echo $?
1
Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71