TransWikia.com

2 values in a variable caused "syntax error in expression"

Unix & Linux Asked on February 21, 2021

Normal case

wolf@linux:~$ x='10'
wolf@linux:~$ if [[ "$x" -eq 10 ]]; then echo True; else echo False; fi
True
wolf@linux:~$ 

My question, let say there are 2 values in y like this

wolf@linux:~$ y=' 10
>   10'
wolf@linux:~$ 

How do I verify if the number in y is equal to 10?

wolf@linux:~$ if [[ "$y" -eq 10 ]]; then echo True; else echo False; fi
bash: [[: 10
  10: syntax error in expression (error token is "10")
False
wolf@linux:~$ 

Is this possible? If not, what is the right way to do it?

p/s – Sorry, not really sure what is the right title for this question. Will change it later (or please change it if you think it’s necessary)

x='10'
y=' 10
   10'
   
if [[ "$x" -eq 10 ]]; then echo True; else echo False; fi
if [[ "$y" -eq 10 ]]; then echo True; else echo False; fi

One Answer

These 2 values are actually different. y is not equal to 10.

x='10'
y=' 10
   10'

That's the reason you're getting False in your output. Echo both variables to see their actual value.

$ echo $y
10 10
$ echo "$y"
 10
   10
$ 

If you want to make it True, try the code shared by alecxs.

for var in $y; do [ "$var" = 10 ] && echo "y=$var true" || echo "y=$var false"; done

Sample output

$ for var in $y; do [ "$var" = 10 ] && echo "y=$var true" || echo "y=$var false"; done
y=10 true
y=10 true
$ 

or, you can also do this way, save it to a file, or run it directly from the terminal

for var in $y; do
 if [[ "$var" = 10 ]]; then
  echo "y=$var True"
 else
  echo "y=$var False"
 fi
done

Sample output

$ for var in $y; do
>  if [[ "$var" = 10 ]]; then
>   echo "y=$var True"
>  else
>   echo "y=$var False"
>  fi
> done
y=10 True
y=10 True
$ 

Correct answer by Sabrina on February 21, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP