1

I was trying to write a shell-script that would print all the arguments passed to the script. The condition is, the argument has to either be an uneven number or smaller than 23

#!/bin/bash
for (( i=0; i<$#; i++ ));
do
        if [[ $i % 2 -ne 0 ]] || [[ $i -lt 23 ]];
        then
                echo $i
        fi
done

When I try to Run this script as followed sh myScript.sh 1 3 4 6 24 23 22 My expected output would be 1 , 3 , 4 , 6 , 22 , 23

However I get the following Error:

myScript.sh: line 4: conditional binary operator expected
myScript.sh: line 4: syntax error near `%'
myScript.sh: line 4: `        if [[ $i % 2 -ne 0 ]] || [[ $i -lt 23 ]];'

Can anyone help me understand what the error means?

Thank you!

11
  • 2
    % is not an operator in [[...]]. Use if ((i % 2 != 0 || i < 23)). Commented Jul 7, 2020 at 20:10
  • @M.NejatAydin Thank you. I tried your suggestion, but I get a different Error now: myScript.sh: line 5: syntax error near unexpected token `then' myScript.sh: line 5: ` then' Commented Jul 7, 2020 at 20:14
  • This is bash code so use bash myScript.sh 1 3 ... Commented Jul 7, 2020 at 20:15
  • Most likely you forgot a semicolon. if ((i % 2 != 0 || i < 23)); then echo $i; fi should work. Commented Jul 7, 2020 at 20:16
  • @TedLyngmo Yes exactly ! Commented Jul 7, 2020 at 20:18

1 Answer 1

1

With Arithmetic Expansion you can do it like this:

#!/bin/bash

for var in "$@"
do
    if (( var%2 || var<23 ))       # arithmetic expansion
    then
        echo $var
    fi
done

Output:

1
3
4
6
23
22
Sign up to request clarification or add additional context in comments.

3 Comments

It should be checking if argv[i] (not i) is odd or less than 23.
@chepner Ok, I must have read his code wrong.... Oh yeah, fixed it.
@TedLyngmo Thank you for your Help! This works fine, and you showed me something new "Arithmetic Expansion".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.