Andrew Luhring Andrew Luhring - 2 months ago 6x
Bash Question

Bash "if" condition being executed no matter what

I'm new to bash scripting, and, while I know this is undoubtably a duplicate question, I can't figure out how to word it to search for it.

for i in $( ls); do
FILETYPE=$( file -b $i )
if [ "$FILETYPE"="Apple binary property list" ]; then
echo "nope"

I'm expecting this to ONLY print

"Apple binary property list"

when the statement succeeds and to ONLY print "nope" otherwise.

What's happening is that it's printing the filetype regardless of whether the statement succeeds or fails, and never prints "nope".

I know it's something simple, but can someone please tell me why it's printing anything other than "Apple binary property list" and "nope",

and what i can do to fix it?


Don't use this:

for i in $( ls); do

as it will break when filenames contain spaces or characters like *. Use this:

for i in *; do

The * expands to the list of all files in the directory.

Don't forget to quote your shell variables, for related reasons:

FILETYPE=$( file -b "$i" )

This passes the whole variable as a single argument, which is what you want.

[ is a command which takes a list of arguments, separated by whitespace:

if [ "$FILETYPE" = "Apple binary property list" ]; then

Without the spaces, [ only sees two arguments, "$FILETYPE"="Apple binary property list" and ].

Again, use quotes around variables:

    echo "$FILETYPE"