Why getting error in bash for loop?

后端 未结 2 908
我在风中等你
我在风中等你 2021-01-17 06:51

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 i

相关标签:
2条回答
  • 2021-01-17 07:04

    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
    
    0 讨论(0)
  • 2021-01-17 07:25

    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
    
    0 讨论(0)
提交回复
热议问题