What is the difference between -lt and < in shell?

Viewed 541

I'm studying shell scripting and don't understand the difference between -eq and ==, -lt and <, -gt and >, so on.

I'm trying to write a while loop printing out from 0 to 9

num=0
while [ $num -lt 10 ]; do
   echo "$num"
   ((num++))
done

This code works but when I change -lt to <, it says No such file or directory.

num=0
while [ $num < 10 ]; do
   echo "$num"
   ((num++))
done

What is the issue with < here? Do I always have to go for -lt in while loops? Is there a general way to do while loops? Appreciate if you can help.

4 Answers

Shell scripting has been always different when it comes to syntax.

so when you say -lt it means less than (<).so when you write your code it works totally fine

while [ $num -lt 10 ]; do
   echo "$num"
   ((num++))
done

But when you use < this in the shell script it is used to read input from file or directory. So here in your case, it will search for the name of the file which is inside the $num variable

In simple words

  1. -lt is Less than which is used for condition checking

  2. < is used for Reading input from the files.

In commandline < means read input from file

for example grep "myname" < data.txt

also, > redirect output to a file

for example ls > lists.txt

when executing $num < 10 it checking for a file named 10

The command [ specifies that -lt should be used to compare two integers. Expecting < to do anything useful is simply wishful.

Coincidentally, the character < is a metacharacter in bash used for input redirection. The error you get is due to the file 10 not existing in your cwd.

You can use '<' with double parentheses (integers) or curly brace (strings)

num=0
while (( $num < 10 )); do
    echo "$num"
    ((num++))
done

and for strings

str="a"
while [[ $str < "aaaaa" ]]; do
    echo "$str"
    str+="a"
done
Related