How to use $# in bool expression in bash?

Viewed 30

I trying to check range regarding to the $# in bash, but I get unexpected result.
I write the following code:

#!/bin/bash
if [[ $# < 2 && $# > 3 ]]; then
   echo "error"
fi

And I trying to running the script such: ./s 1 2 3 4 5 6 but I don't get the "error" message.
What is the reason of that?

1 Answers

That's because you are comparing strings, to compare integers you need an arithmetic expression (( e )):

if (( $# < 2 && $# > 3 ))

Also, it's impossible for a number to be less than 2 and greater than 3, you meant or:

if (( $# < 2 || $# > 3 ))

Also, you don't need an arithmetic expression, you can use -lt (less than) and -gt (greater than):

if [[ $# -lt 2 || $# -gt 3 ]]
Related