1

Following script

read n
for (( c=1; c<=$n; c++ ))
do
    echo "HI"
done

gives error solution.sh: line 2: ((: c<=1: syntax error: invalid arithmetic operator (error token is "")

I am using BASH. What is wrong with the for loop?

edit: I am working on the BASH hackerrank IDE and although this code is not directly related to the problem in this link, I am getting this error.

picasso13
  • 11
  • 1
  • 5
  • 1
    Did you add `#!/bin/bash` top line? – Déjà vu Jul 05 '18 at 05:35
  • Tested this in GIT Bash installed in Windows 10 along with `gnuwin32`. Works flawlessly. I would also suggest verifying if `#!/bin/bash` is present at the top of the bash script. – Romeo Sierra Jul 05 '18 at 05:43
  • Can you `cat -v solution.sh` and make sure there are no funny characters in it? – that other guy Jul 05 '18 at 05:53
  • 1
    I am getting this error on the [hackerrank IDE](https://www.hackerrank.com/challenges/lonely-integer-2/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen) but it is good to know that the loop is alright. Thank you. – picasso13 Jul 05 '18 at 06:20

3 Answers3

0

I've reproduced this error message by pressing Ctrl-E after 1. It looked like this:

$ ./1.sh 
1^E
./1.sh: line 3: ((: c<=1: syntax error: invalid arithmetic operator (error token is "")

So make sure you are not pressing some strange combination of keys before enter.

Karol Samborski
  • 2,757
  • 1
  • 11
  • 18
  • Could this be an internal error on the [Hackerrank IDE](https://www.hackerrank.com/challenges/lonely-integer-2/problem?h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen) ? I am getting the error there. But thank you so much. – picasso13 Jul 05 '18 at 06:23
0

You need to add this line

#!/bin/bash

at the top of solution.sh.

(if your bash is at a different location, do, in a terminal,

which bash

to determine its location)

Déjà vu
  • 28,223
  • 6
  • 72
  • 100
0

@picasso13 just a wild guess cause it got me(and yield the same mysterious error when I tried to loop with array constructed from the input). There are 2 inputs on hackerRank(the first one is actually the size of the second). It solved my problem when I threw away the first and make sure my iteration was working on the list of numbers:

freq=()
for i in {1..100}; do
    freq[$i]=0
done    
read ignore
read inputs
IFS=', ' eval 'array=($inputs)'


for i in "${array[@]}"; do 
    (( freq[$i]++ )) 
done
for i in "${!freq[@]}"; do
    if [[ freq[$i] -eq 1 ]]; then
        echo $i
    fi
done

if you comment out my read ignore you'll reproduce the issue.

HoaPhan
  • 1,714
  • 1
  • 13
  • 35