Search code examples
jsonbashjqmediainfo

Bash case statement doesnt work with json string value using jq


I working on a function which extract the choosen track from a media container (mkv,mp4...etc). One of its major feature will be the "auto output file extension assigner".

the process will be the following...

step 1) when i give the script the number of the track, which i want to extract, it automatically inspect the source file with mediainfo and output the results in JSON format.

step 2) With JQ, i query the value of the "track" key from the selected track, and save it to the "mediaFormat" variable.

step 3) put this variable in a switch statement and compare with a predefined list of switches. If there is a match, then it will initialize the "mediaExtension" variable with the appropriate value, which will be used as a extension of the ouput file.

For now i just want echo the "mediaExtension" variable, to see if it works. And it DIDN'T WORK.

The problem is step 1-2 works as expected, but somehow the switch statement (step 3) doesn't work. Only the (*) switch will be executed, which means it doesn't recognize the "AVC" switch.


#!/bin/bash


# INCLUDES

# mediainfo binary

PATH=/cygdrive/c/build_suite/local64/bin-video:$PATH;

# jq binary

PATH=/cygdrive/c/build_suite/local64/bin-global:$PATH;


# BASH SETTINGS

set -x;


# FUNCTION PARAMETER

function inspectExtension () {


mediaFormat=$(mediainfo "$1" --Output=JSON | jq ".media.track[$2].Format");


case $mediaFormat in

    "AVC") mediaExtension="264";;

        *) echo "ERROR";;    

esac

set "$mediaExtension";

echo "$mediaExtension";

}

inspectExtension "test.mp4" "1";


read -p "Press enter to continue...";

And as you can see, in this script i activated tracing (set -x), and this is what i see in the console window (i use cygwin on windows 10).

+ inspectExtension test.mp4 1
++ mediainfo test.mp4 --Output=JSON
++ jq '.media.track[1].Format'
' mediaFormat='"AVC"
+ case $mediaFormat in
+ echo ERROR
ERROR
+ set ''
+ echo ''

+ read -p 'Press enter to continue...'
Press enter to continue...

Any ideas? Or is something what i miss here?

Thx for the help!


Solution

  • Maybe the only thing you miss is using the --raw-output option of jq like so:

    mediaFormat=$(mediainfo "$1" --Output=JSON | jq --raw-output ".media.track[$2].Format");
    

    Whenever you use jq to access some string values, it will be best to use the --raw-output option because it get's rid of the enclosing quotes.