Mac – Merge audio and video in a monitored folder

audiobashmacsshterminal

I want to create a script on mac that monitors a folder and merge the video and the audio.
But if file01 exists (previous merge file) I want it to create file02 and if this one exists I want it to create file03,… I would be very happy if the older files could be deleted because of disk space. But this one is tricky because I monitor the folder through folder action setup on mac. This is what I get so far:

#!/bin/bash
now=$(date +"%d_%m_%Y_%Hu%M")
cd "/Users/tomvanwinkel/Documents/Convert/Merge"
for filename in *.mp4; do
    stub="${filename%.*}"
    /usr/local/bin/ffmpeg -i "${stub}.mp4" -i "${stub}.wav" -c:v copy -c:a aac -map 0:v:0 -map 1:a:0 "${stub}_ok".mp4

    FILE="${stub}_ok".mp4
    if [ -f "$FILE" ]; then
        cp "${stub}_ok".mp4 "${stub}_ok01".mp4
    fi
done

Best Answer

Creating target files in the watched folder is asking for trouble, so I would create them "outside" instead:

#!/bin/bash
now=$(date +"%d_%m_%Y_%Hu%M")
cd "/Users/tomvanwinkel/Documents/Convert/Merge"
mkdir -p ../Target
for filename in *.mp4; do
    stub="${filename%.*}"
    target="../Target/${stub}_ok_$(date +%Y-m%-%d_%H)"

    /usr/local/bin/ffmpeg -i "${stub}.mp4" -i "${stub}.wav" -c:v copy -c:a aac -map 0:v:0 -map 1:a:0 "${target}.mp4"

    rm -f "${stub}.mp4" "${stub}.wav"
done