Common Pitfalls

unary operator expected


if [ $thisVar -eq $thatVar ] then // processing fi if [ -eq 5 ] then...

What does this mean? It means the shell is looking for a variable and found nothing. Not an empty variable, nothing. Take this structure:




If one of the variables is empty, the shell wips out the old unary operator expected error which can be a fault tollerant but can mess up the flow.

The reason this happens is because the arguments were not quoted. This is a common pitfall excpecially for those comming from more structured languages. Re-examining the above example, lets say thisVar was empty and thatVar was 5; what the shell sees is:


This situation can be avoided with a set of quotes. If bot variables were quoted the tables would be turned because the shell would see... if [ -eq 5 ] then...


and the old unary operator expected would never be thrown.

CREATED 2017-09-04 20:01:23.0

00-2A-90

UPDATED 2019-02-28 23:42:16.0

value too great for base


varA="09" [[ "$varA" -gt 0 ]] && do something || do something else ...line 197: [[: 09: value too great for base (error token is "09") varA="09" [[ $((10#$varA)) -gt 0 ]] && do something || do something else

It's the old value too great for base (error token is ... trick! Whaa? This is a pretty simple problem and it has to do with the fact that bash is weakly typed. There for a number and a string are almost the same thing but treated differently at run time depending on how they are being used.

So... what does it mean? It means that the variable in question begins with a zero and the value is greater than 7 (C style). Bash treats numbers begining with a zero as octal just like a x is treated as hexidecimal. So if the variable in question is 08 and you are trying to do a comparison on that variable in a decimal format, bash throws this error because 08 is not a proper octal number. (0 thru 7 only).




This throws the old value too great for base error because bash is treating varA as an octal number.

What to do about it? Cast the number to decimal by preceeding it with 10#:



This will cast varA as a decimal before doing the comparison. It's a mathmatical equation so it needs to be wrapped in double parens.

NOTE: This solution only works in Bash 3.0 or higher. Below that just strip the leading 0 off ${varA#0}

CREATED 2018-12-23 14:06:04.0

007-00-00-B0

UPDATED 2019-03-01 00:34:24.0

Knowledge

L
I
N
K
S

DBID: db.wam

Page Server: Ithica

©2012 Leistware Data Systems

      Hello anonymous