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?