Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

What is the problem with the following shell script? I'm getting

[: too many arguments

error

#!/bash
var1=10;
var2=20;
if [ $var1 % 2 -eq 0 ] -a [ $var2 %5 -eq 0 ];
then
    #something
fi
share|improve this question
1  
Why do you believe that % and %5 are valid arguments for [? –  Ignacio Vazquez-Abrams Jan 6 '12 at 7:06
    
how do we get the modulous (I am a newbie) –  Pradeep Jan 6 '12 at 7:10
add comment

2 Answers 2

First, the [ command only does comparisons. You have to perform calculations separately. For example:

var1mod=$((var1 % 2))
if [ $var1mod -eq 0 ]; then

However, since you appear to be writing your script for bash, you can use a different command and avoid the extra step:

if (( var1 % 2 == 0 )); then

And second, you cannot chain commands with -a. This only works as an argument to [. But outside it, you must use &&.

Three different variants:

if [ $var1mod -eq 0 -a $var2mod -eq 0 ]; then
if [ $var1mod -eq 0 ] && [ $var2mod -eq 0 ]; then
if (( var1 % 2 == 0 )) && (( var2 % 2 == 0 )); then
if (( var1 % 2 == 0 && var2 % 2 == 0 )); then

Always remember, the syntax of if is a simple if command; then command; fi. This means that [ in if [ is just the name of a command like ls or echo.

share|improve this answer
add comment

You seem to be confusing Conditional Evaluation with Arithmetic Evaluation. % is an operator in Arithmetic Evaluation, not Conditional Evaluation. See the bash(1) man page sections for those topics. [...] is for Conditional Evaluation, whereas ((...)) is for Arithmetic Evaluation.

Not to mention that your shebang line is wrong, unless for some reason you installed a copy of bash at the root level of your boot drive.

Last but not least, a newline is the same as a semicolon. You don't need to end a line with a semicolon in shell scripting. The semicolon just exists to allow you to put two statements on one line.

Here's a cleaned up version of your script:

#!/bin/bash

VAR1=10
VAR2=20
if (( (VAR1 % 2 == 0) && (VAR2 % 5 == 0) )); then
    : #something (colon is a no-op)
fi
share|improve this answer
    
-a has two meanings; EXPR -a EXPR is a logical AND. –  grawity Jan 6 '12 at 8:17
    
Thanks @grawity. Fixed. –  Spiff Jan 6 '12 at 8:24
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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