syntax error near unexpected token `do' in bash script
For me, it was due to CRLF
. It should be LF
for linux env.
There are a bunch of syntax errors here. Let's start with the line:
if[ ( ${file: -4} == "$1" ) || ( ${file: -4 } == "$2" ) ]{
You need a space between
if
and[
(or whatever comes after it). As written, the shell is treating "if[" as the name of a command, which isn't what you want at all.The
[ ... ]
style of conditional doesn't understand||
(it uses-o
instead), requires that all shell metacharacters (like parentheses) be escaped or quoted, might not understand==
(just=
is the standard), and will get very confused if any of the unquoted variable/parameter references are blank.if
conditionals end withthen
(either on the next line, or after a;
) not{
You could fix it like this:
if [ \( "${file: -4}" = "$1" \) -o \( "${file: -4}" = "$2" \) ]; then
Or, since you're using bash
(instead of a more basic shell), you can use the [[ ... ]]
conditional style, which has much cleaner syntax:
if [[ "${file: -4}" = "$1" || "${file: -4}" = "$2" ]]; then
Next, remove the do
before ffmpeg
. do
is part of the syntax for for
and while
loops; you already have one above (where it belongs), and this one just doesn't make sense. This is what's causing the error you see.
Next, the way you're replacing the file's extension won't work right. The variable reference "${file%.extension}"$3
will try to remove ".extension" (not the variable, just the string) from the end of $file
. It also has $3
outside the quotes, which can cause trouble. You could fix it by using "${file%$extension}$3"
instead, but frankly I'd just use "${file%.*}$3"
to remove the extension no matter what length it is (and I'd also redo the if
comparisons similarly, but that's more complicated).
Finally, you need a fi
(after the ffmpeg
line) to end the conditional. Every if
needs a then
and a fi
.
And just as a stylistic thing, you don't need ;
at the end of a line in shell; it's only needed when you're putting multiple commands (or things like do
and then
) on the same line. Anyway, here's my quick rewrite:
#!/bin/bash
# $1 is the first parameter passed
# $2 is the second parameter passed
# $3 is the third parameter passed
for file in *.*; do
#comparing the file types in the directory to the first 2 parameters passed
if [[ "${file: -4}" = "$1" || "${file: -4}" = "$2" ]]; then
#converting such files to the type of the first parameter using the FFMPEG comand
ffmpeg -i "$file" "${file%.*}$3"
fi
done