Shell IF statement in Bash Script has errors in terms of the brackets


New Member

Messages: 1

if [[ $num =~ ^[+-]?[0-9] +$ ] || $num=0 ]; then

the bracket after $num=0 is blacked out meaning there is something wrong with the condition format, can someone help me to identify why its like that?


Son of Beastie

Reaction score: 1,985
Messages: 2,945

I don't know what "blacked out" means. But let's look. I'll copy this into a line that's fixed width font, so I can put comments exactly under things:
if [[ $num =~ ^[+-]?[0-9] +$ ] || $num=0 ]; then
   1                                 2    3            4   5

1. Why are you using [[? There is some old folklore that it is faster than [, but that's not true any longer. I would simplify this to using a single opening bracket. (However, there is some subtle difference between [[ and [ which I forget).

2. You have a space in the middle of the regular expression. Is that a mistake? Do you mean one digit, and then one or more spaces, or do you mean one or more digits? And if you want to have a space in the regular expression, you nave to quote it: "$num" =~ "^[+-]?[0-9] +$". I think you also need to quote or escape the $ sign, otherwise it will be interpreted as wanting a variable name afterwards.

3. At this point, there is a closing square bracket. What are you trying to close here?

4. You are trying to test whether a variable is zero. In order for the shell to parse this, you need to break the test "$num = 0" into three tokens, which needs spaces around the equal sign. Also, are you going for a string or numeric comparison? For example, do you want 00 to mean zero, or +0, or -0? The equal sign will do a string comparison, so none of those will test as equal. You probably want to do "$num -eq 0", which will do a numeric comparison.

5. You opened your test with double square brackets, you are closing it with a single one. Either use double brackets both sides, or single brackets.

In general, programming shell is about the art of quoting. What if the string $num contains bizarre characters? How are you going to prevent it form having a newline or space in it? I would rewrite this as "if [ "$num" =~ "..." || "$num" -eq 0]", so things in the variable are suitably protected.