0

I am trying to run the below code using for loop but i am getting syntax error. Please help.

Input Format: The first line of the input contains an integer N, indicating the number of integers. The next line contains N space-separated integers that form the array A.

read n
sum=0

for (( i=1; i<= "$n" ; i++ ))
do
        read val
        sum ^= $val;
done

echo $sum

Below is the error message

solution.sh: line 4: ((: i<= 1
 : syntax error: invalid arithmetic operator (error token is "
 ")
18
  • 1
    DOS line-endings in your script file? Commented Jun 11, 2015 at 15:28
  • 1
    @User112638726 Using $ is valid in that context though (despite being unnecessary most of the time) and is not the error. Commented Jun 11, 2015 at 15:30
  • 1
    @User112638726 Nope. Works just fine. Try it yourself. Commented Jun 11, 2015 at 15:33
  • 1
    Add printf "%s" "$n" | hexdump -C before the while loop; what output does it produce? Commented Jun 11, 2015 at 15:39
  • 2
    The 0d is a carriage return. Your script file contains DOS newlines as suggested by Etan. Run dos2unix on your script, or use your favorite text editor to save the file with Unix newlines. Commented Jun 11, 2015 at 15:50

2 Answers 2

1

The printf "%s" "$n" | hexdump -C shows that the CR is contained in the input rather than in the script file, so running dos2unix on the script won't help anyway. A simple means to get rid of it is setting IFS=$'\r'.
Then, read val in a loop is unfit to read space-separated integers, since read reads a whole line at a time. But for the task of bitwise exclusive ORing those N space-separated integers we don't need an explicit loop - we can just replace all spaces with the desired operator and evaluate the result.

#!/bin/bash
IFS=$'\r'
read n
read a
((sum = ${a// /^}))
echo $sum
Sign up to request clarification or add additional context in comments.

Comments

0

This will work. However you should insert some helper messages inside:

#!/bin/bash

read n
sum=0

for (( i=1; i<=n; i++ ))
do
        read val
        ((sum^=val))
done
echo $sum

4 Comments

^= is a valid bash arithmetic context assignment operator (though not with the spaces obviously) but this doesn't solve the actual problem the poster is having.
Still getting this error solution.sh: line 4: ((: 1 : syntax error: invalid arithmetic operator (error token is " ")
It look like there is problem with for loop. why it is giving invalid arithmetic operator?
@Kikit: try dos2unix solution.sh and the rerunning my example. Etan Reisner: thanks for the note (corrected).

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.