Strings comparing incorrectly

Hello I'm very new to Linux and shell scripting so I only know basic stuff. I'm making a script with the purpose of finding the longest string or word in a file. Here's what I got so far:

#!/bin/bash 
longest=""
for i in $(strings -n $1); do

if  [[ $longest < $i ]]
then 
 longest=$i
fi
done
echo $longest

So basically the script will use a file given in the command line which contains words and then return the longest one.

This is the file I'm using to test it out it's called test:

apples
are
the
best
in
the
world

now I run it with bash -x script2 test
so I can see what's happening and this is what I get:

+ longest=
++ strings -n 1 test
+ for i in '$(strings -n 1 $1)'
+ [[ '' < apples ]]
+ longest=apples
+ for i in '$(strings -n 1 $1)'
+ [[ apples < are ]]
+ longest=are
+ for i in '$(strings -n 1 $1)'
+ [[ are < the ]]
+ longest=the
+ for i in '$(strings -n 1 $1)'
+ [[ the < best ]]
+ for i in '$(strings -n 1 $1)'
+ [[ the < in ]]
+ for i in '$(strings -n 1 $1)'
+ [[ the < the ]]
+ for i in '$(strings -n 1 $1)'
+ [[ the < world ]]
+ longest=world
+ echo world
world

So by the looks of it it's just replacing the value of the current word with the next one.
So my question is how can I accurately compare the words so it returns the longest one?
I'm guessing my mistake is in this line:

if  [[ $longest < $i ]]
#! /bin/bash

longest=""
charCount=0

while read x
do
    if [ $charCount -lt ${#x} ]
    then
        charCount=${#x}
        longest=$x
    fi
done < $1

echo "Longest Word: $longest; Number of Chars: $charCount"

The more modern syntax is

while read x
do
    if (( charCount < ${#x} ))
    then
        charCount=${#x}
        longest=$x
    fi
done < $1

Minor nitpick:

done < "$1"

Otherwise it will break for filenames with spaces or strange characters..

It is keeping the one that is lexically greater. If somehow the shorter string were padded with leading spaces to make them equal length, then your comparison would work, if you enclosed both variables in double quotes. But doing so would involve knowing the length of the larger of the two variables and that's what you were set to find out in the first place :slight_smile:

$ [[ "bbb" < "aaaa" ]] && echo hello
$ [[ " bbb" < "aaaa" ]] && echo hello
hello

Works like a charm now. Thank you for the help :b:, didn't know it would be so much easier using a while loop.