为什么在bash for loop中出错? [英] Why getting error in bash for loop?

查看:69
本文介绍了为什么在bash for loop中出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用for循环运行以下代码,但出现语法错误.请帮忙.

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

输入格式: 输入的第一行包含一个整数N,表示整数的数量.下一行包含形成数组A的N个以空格分隔的整数.

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

下面是错误消息

solution.sh: line 4: ((: i<= 1
 : syntax error: invalid arithmetic operator (error token is "
 ")

推荐答案

printf "%s" "$n" | hexdump -C显示CR包含在输入中而不是脚本文件中,因此在脚本上运行dos2unix仍然无济于事.摆脱它的一个简单方法是设置IFS=$'\r'.
然后,循环中的read val不适合读取以空格分隔的整数,因为read一次读取整行.但是对于按位异或这些 N个空格分隔的整数的任务,我们不需要显式循环-我们只需用所需的运算符替换所有空格并评估结果即可.

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

这篇关于为什么在bash for loop中出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆