0

I have tried to execute the code below on my Ubuntu machine, but it keeps saying "syntax error in conditional expression" and "syntax error near '0-9'" can you tell me why?

While ! [[ $num =~ ^[ 0-9 ] +$ && $num = 0 ]] ; do 
1
  • [[ $num = 0 ]] is string comparison, so having it there makes the regex match useless. If you want to check if the variable is nonempty and compares as zero, you could use [[ -n $num && $num -eq 0 ]] or [ -n "$num" ] && [ "$num" -eq 0 ]. Either would accept stuff like 000 and 000 , but not the empty string.
    – ilkkachu
    Jun 8 at 13:58

1 Answer 1

5

Your while shouldn't be capitalized but I think that only happened when typing into this question otherwise you would get a different error.

Your issue is likely just that your regular expression is wrong.

[ 0-9 ] should be [0-9] with no spaces. Once you fix that however you will get a different error about +$ because you will also need to escape the space between them.

while ! [[ $num =~ ^[0-9]\ +$ && $num = 0 ]] ; do 

It's often better to store patterns like this in a variable for use with the extended test:

pattern='^[0-9] +$'
while ! [[ $num =~ $pattern && $num -eq 0 ]]; do
1
  • 1
    ...and note that you here, you must not quote $pattern, since otherwise it's taken as literal and not a regex.
    – ilkkachu
    Jun 8 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.