1

this is my first "if-else" script on linux. It gives the error
[: too many arguments

Code:

n=0
if [ $n % 2 -eq 0 ]
then
  echo "even number"
fi 

How to correct it.

3

Math in bash must be performed in arithmetic context. In your current implementation, you are supplying "$n", "%", and "2" as args to [, which does not perform math. Here is an example which performs that math n arithmetic context:

if [ "$((n % 2))" -eq 0 ]

In the above example, the results of the $(()) are expanded by the shell before it is seen by the [ command. You can simplify this by removing the call to [:

if (( (n % 2) == 0 ))
2
  • Thank You.The first method worked. But i just used the following line which also worked. if [ expr $n % 2 -eq 0 ] this is causing some confusion.
    – Pradeep
    Feb 2 '15 at 14:48
  • @Pradeep in [ expr $n % 2 -eq 0 ] you are calling test using six arguments. Hence the rule covering five or more arguments applies: "The expression is parsed and evaluated according to precedence using the rules listed above." (Bash Reference) Evaluating 'expr $n % 2' brings that down to three parameters and then the rule for 3 arguments applies.
    – Arjen
    Feb 14 '19 at 0:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.