bash

bash script : test for video files failed


I have written a little bash script to extract audio from video files in batch mode.

Sound is extracted from each mp4 file to flac format using avconv (and the flac codec).

#!/bin/sh
#
# Batch conversion of audio extraction from video

FOLDER_SRC="/home/Me/Music/TestBatchConv"

for myvid in $(find ${FOLDER_SRC} | grep mp4)
do
avconv -i $myvid -acodec flac "${myvid}.flac"
done

exit 0

It works fine, but I would like to improve it.

How do I test if the file is a video? I tried something like

for myvid in $(find ${FOLDER_SRC})
do
    if [ file -i $myvid | grep video ]
        then avconv -i $myvid -acodec flac "${myvid}.flac"
    fi
done

but I can't get it done.


Solution

  • rewrite your new test as

     if  file -i $myvid | grep -q video  ; then
    

    The -q option means quiet, so grep returns true if it finds the search target and false if not. The if responds appropriately depending on the true or false state that is returned.

    Braces used with if statements are really an alias tot the test cmd, so something like

      if [ $(file -i $myvid | grep video) = "video" ] ; then
    

    would also work.

    To learn how to get this sort of thing right, just work on the command line, and add one bit at a time, i.e.

     file -i $myvid 
    

    then

    file -i $myvid | grep video
    

    OR

    file -i $myvid | grep -q video ; echo $?
    

    And to see the inverse, change to

    file -i $myvid | grep nonesuch ; echo $?
    

    EDIT

    And to test for more than one thing, you can use egrep, i.e.

     if  file -i $myvid | egrep -q 'video|application/octet'  ; then
    

    IHTH