AndriusWild
AndriusWild

Reputation: 81

Bash - catch the output of a command

I am trying to check the output of a command and run different commands depending on the output.

count="1"
for f in "$@"; do
   BASE=${f%.*}
#    if [ -e "${BASE}_${suffix}_${suffix2}.mp4" ]; then
    echo -e "Reading GPS metadata using MediaInfo file ${count}/${#@} "$(basename "${BASE}_${suffix}_${suffix2}.mp4")"
   mediainfo "${BASE}_${suffix}_${suffix2}.mp4" | grep "©xyz" | head -n 1
    if [[ $? != *xyz* ]]; then
    echo -e "WARNING!!! No GPS information found! File ${count}/${#@} "$(basename "${BASE}_${suffix}_${suffix2}.mp4")" || exit 1
    fi
    ((count++))
done

MediaInfo is the command I am checking the output of. If a video file has "©xyz" atom written into it the output looks like this:

$ mediainfo FILE | grep "©xyz" | head -n 1
$ ©xyz                                     : +60.9613-125.9309/
$

otherwise it is null

$ mediainfo FILE | grep "©xyz" | head -n 1
$

The above code does not work and echos the warning even when ©xyz presented. Any ideas of what I am doing wrong?

Upvotes: 0

Views: 616

Answers (2)

Inian
Inian

Reputation: 85560

The syntax you are using the capture the output of the mediainfo command is plain wrong. When using grep you can use its return code (the output of $?) directly in the if-conditional

if mediainfo "${BASE}_${suffix}_${suffix2}.mp4" | grep -q "©xyz" 2> /dev/null; 
then
..

The -q flag in grep instructs it to run the command silently without throwing any results to stdout, and the part 2>/dev/null suppresses any errors thrown via stderr, so you will get the if-conditional pass when the string is present and fail if not present

Upvotes: 1

that other guy
that other guy

Reputation: 123410

$? is the exit code of the command: a number between 0 and 255. It's not related to stdout, where your value "xyz" is written.

To match in stdout, you can just use grep:

if mediainfo "${BASE}_${suffix}_${suffix2}.mp4" | grep -q "©xyz"
then
  echo "It contained that thing"
else
  echo "It did not"
fi

Upvotes: 0

Related Questions