0

I'm trying to create a bash script to run the ffmpeg command on every file in a directory with filenames that contain spaces. This is the script that I started with to do an individual file which works properly. I use tab to populate the filename argument which includes an escape character for all the spaces:

#!/bin/bash
input="./"$1
output="/xfer/transfer/temp/"$1
ffmpeg -i "${input}" -c:v copy -c:a libfdk_aac -b:a 160k "${output}"

Next step is to perform the ffmpeg command on all files in a directory. Let's say the directory looks like this with the ls command:

'Name of First File.mkv'
'Name of Second File.mkv'

Here's my test code:

#!/bin/bash
files=$(ls *)

for input in ${files} do echo $input done

My problem is the output looks like this:

Name
of
First
File.mkv
Name
Of
Second
File.mkv

Adding a -b to the ls command simply adds a backslash to the end of every line. I need help with making $input look like Name of First File.mkv, etc.

1 Answers1

0

As pointed out in the comments, quote your parameters expansions and do not loop through ls output. Unquoted file names could split if they contain any of the characters in the IFS shell variable.

The following code could solve your problem:

for file in *; do
    ffmpeg -i "${file}" -c:v copy -c:a libfdk_aac -b:a 160k "/xfer/transfer/temp/${file}"
done

Be careful when replacing the pattern in the loop; it may expand to a list of pathnames with slashes which would be concatenated with the string /xfer/transfer/temp. To prevent that, you may do the following:

for file in otherdirectory/*; do
    ffmpeg -i "${file}" -c:v copy -c:a libfdk_aac -b:a 160k "/xfer/transfer/temp/$(basename "${file}")"
done

If you need to recurse the directory even deeper, set the globstar option with the shopt command builtin.

Kusalananda
  • 333,661
qqqq
  • 48