Why getting error in bash for loop?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-30 14:20:12

问题


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 "
 ")

回答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



回答2:


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


来源:https://stackoverflow.com/questions/30785034/why-getting-error-in-bash-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!