0

I know I'm missing something very obvious, but I just can't see it. In the code below, new_i variable gets incremented properly, however, when I get to the if statement, I think my syntax is off. I looked at some examples, but none show variable set to zero when if statement is greater than (in this case 15) a number.

#!/bin/sh
i=$(cat /etc/hour.conf)
new_i=$((i+1))
if [[ "$new_i" -gt 15 ]]; then
 new_i=0
fi
echo "$new_i">/etc/hour.conf
echo "$new_i"

When I run this script I get the following error:

./loops: 3: ./loops: Illegal number: new_i

Thanks in advance for your help!

13
  • Remove space after =: new_i=0 Commented Jun 16, 2017 at 14:22
  • that gives the same error message Commented Jun 16, 2017 at 14:23
  • Ah, the problem is on line 3... What is content of /etc/hour.conf? Commented Jun 16, 2017 at 14:27
  • echo 0>/etc/hour.conf Commented Jun 16, 2017 at 14:28
  • Hm.. Can you cat that file? echo 0>x.txt && cat x.txt gives me empty file. To fix it you have to add space before >: echo 0 >/etc/hour.conf Commented Jun 16, 2017 at 14:30

2 Answers 2

2

This works - the $ in front of the i in the new_i=$(( line and the removal of the quotes and one set of the brackets fixed the errors and now the scripts works as intended. Thanks to everyone for their help!

#!/bin/sh
i=$(cat /etc/hour.conf)
new_i=$(($i+1))
if [ $new_i -gt 15 ]; then
 new_i=0
fi
echo "$new_i">/etc/hour.conf
echo "$new_i"
Sign up to request clarification or add additional context in comments.

4 Comments

$((i+1)) works the same as $(($i+1)) if i is a valid number. And the code you posted works if I change the filename to x.txt and set it initial content to empty.
Glad we helped... but really not clear how we did it, haha ;)
$((i+1)) is definitely valid out-of-the-box.
As for [[ ]] vs [ ], the former requires a different shebang -- it'll work with #!/bin/bash, for example; just not #!/bin/sh.
0

Try without the quotes:

if [ $new_i -gt 15 ]; then
    ...
fi

or, better yet, use arithmetic evaluation instead:

if (( $new_i > 15 )) ; then
    ...
fi

7 Comments

different error ./loops Illegal number:new_i
-get i think it is a typo
I used -gt when I tested.
(( $new_i > 15) gave the same error.... ./loops: Illegal number: new_i
What difference does removing the quotes make if the variable doesn't contain a valid number?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.