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 ]]
, didn't know it would be so much easier using a while loop.