samedi 30 septembre 2017

If-statements in Bash Syntax issues produce right answers, while right code shows wrong answers

I am fairly new to bash scripting and am struggling with some if-statement syntax.

I have currently written up the following loop:

for (( i = 2; i < $# - 1; i++)); do
    if [ $i -ne 0]; then
        if [ $i -ne 1]; then
            echo "$i was not 1 or 0. Please correct this then try again."
            exit 1;
        fi
    fi
done

This code is supposed to test whether any arguments after the first are either a 1 or a 0.

While the following errors are printed:

./blink.sh: line 36: [: missing `]'
./blink.sh: line 36: [: missing `]'

...the code actually runs fine afterwards (so the errors don't kill the program).

My understanding, however, is that in bash, you put spaces before and after the expression inside the if statement. So this:

if [ $i -ne 0]; then

Becomes:

if [ $i -ne 0 ]; then

However, running this code produces the following:

2 was not 1 or 0. Please correct this then try again.

This does not change regardless of what the actual arguments are. Changing the if statement to double brackets does not change the answer here. So I'm unsure either where my code is wrong or what is happening when I have the broken code that is still causing it to get to the right answers.

Thanks!

Aucun commentaire:

Enregistrer un commentaire