Reputation: 1914
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 $FILETYPE
else
echo "nope"
fi
done
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?
Upvotes: 0
Views: 164
Reputation: 74695
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"
Upvotes: 2
Reputation: 409452
The problem is that the square-bracket [
is a command, it's an alias for the test
command, and as all commands it expects its arguments to be separated by spaces.
When you write (without any spacing)
"$FILETYPE"="Apple binary property list"
that is a single argument to the test
command, and it uses that single arguments as a non-empty string which will always be true.
When you add spaces, like
"$FILETYPE" = "Apple binary property list"
the test
command has three arguments and will parse it correctly as a string, an operation and another string.
Upvotes: 0