Skip to main content
added 11 characters in body
Source Link
cas
  • 83.9k
  • 8
  • 136
  • 205

I also modified the script to avoid horizontal scrolling on SE due to long lines.

I also modified to avoid horizontal scrolling on SE due to long lines.

I also modified the script to avoid horizontal scrolling on SE due to long lines.

Source Link
cas
  • 83.9k
  • 8
  • 136
  • 205

Example modified script writing to local /tmp, then moving to the server if the transcode was successful:

#!/bin/bash

# Rescale files in subdirectories (Kodi library) using 1334
# as driving width from which height is calculated.
# Output format is mkv.

for directory in * ; do
  [[ -d "$directory" ]] || continue
  for file in "$directory"/*.{mkv,mp4,mpg,webm} ; do
    [[ -e "$file" ]] || continue
      filename=$(basename "$file")
      output_file="/tmp/${filename%.*}-w1334.mkv"

      ffmpeg -i "$file" -map 0 -codec:a copy \
        -codec:s copy -codec:v h264_nvenc -gpu 1 \
        -filter:v scale="1334:-2" "$output_file" &&
            mv "$output_file" "$directory"
  done
done

I also modified to avoid horizontal scrolling on SE due to long lines.

I find this also makes long and complicated command lines like those often used with ffmpeg to be much more readable and easier to understand and debug and modify.

Another bash script readability tip with commands like ffmpeg (and rsync and many others where long command lines are common) is to put some or all of the args in an array (do this before the main loop, it only needs to be done once, not repeatedly) and use "${arrayname[@]}" in the ffmpeg command line, e.g.

#!/bin/bash

# Rescale files in subdirectories (Kodi library) using 1334
# as driving width from which height is calculated.
# Output format is mkv.

ffargs=(-map 0
        -codec:a copy
        -codec:s copy
        -codec:v h264_nvenc
        -gpu 1
        -filter:v
        scale="1334:-2"
       )

for directory in * ; do
  [[ -d "$directory" ]] || continue
  for file in "$directory"/*.{mkv,mp4,mpg,webm} ; do
    [[ -e "$file" ]] || continue
      filename=$(basename "$file")
      output_file="/tmp/${filename%.*}-w1334.mkv"

      ffmpeg -i "$file" "${ffargs[@]}" "$output_file" &&
          mv "$output_file" "$directory"
  done
done

BTW, I'm not sure why you're bothering to check if the input file exists - the script is looping over filenames found in the directory, so it's pretty much guaranteed to exist. If you need that at all, it might be more useful to check that it's a regular (i.e. not a symlink or pipe or whatever), non-empty file that is readable by your uid rather than just testing for existence, e.g. instead of [[ -e "$file" ]]:

[[ -f "$file" && -s "$file" && -r "$file" ]] || continue

And maybe also check if the directory is both readable & writable by you:

[[ -d "$directory" && -r "$directory" && -w "$directory" ]] || continue