Atomiklan
Atomiklan

Reputation: 5434

Test if string is "*"

For some reason I just cannot get an if statement to test if a string is literally equal to an asterisk. I have tried every combination I can think of and I don't want to mess with file globbing. Please help.

if [ $VAR = "\*" ]; then

* UPDATE *

Both of those suggestions work. The issue is apparently not with the * comparison, but with the other part of the if statement. This is supposed to compare whether or not $VAR is between 0 and 20 or is a wildcard.

if [ "$VAR" -gt 0 ] && [ "$VAR" -lt 20 ] || [ "$VAR" = "*" ]; then

This other part of the IF statement if apparently goofing up the last comparison.

* UPDATE *

Just tested it again and checked my syntax. When $VAR is between 0 and 20 it works great (true), when $VAR is over 20 it also works (reports false), however as soon as I try to set $VAR to an * the if statement freaks and pops out:

line 340: [: *: integer expression expected

Upvotes: 1

Views: 1315

Answers (2)

Yossarian
Yossarian

Reputation: 5471

Another version using bash's double brackets:

if [[ $VAR = "*" || ($VAR -gt 0 && $VAR -lt 20) ]]; then

The double brackets allow you to use && and ||. Also, bash doesn't perform word splitting or glob expansion on arguments to [[, so $VAR doesn't need to be quoted and ( doesn't need to be escaped.

[[ also works in zsh and ksh, if you need (some) portability.

Upvotes: 1

Mat
Mat

Reputation: 206709

$ VAR="*"
$ if [ "$VAR" = "*" ] ; then echo Star ; fi
Star

Quote variables when they could contain glob patterns, whitespace or other interpretable sequences you don't want interpreted. This also avoids syntax errors if $VAR is empty.

For your second problem, [ "$VAR" -gt 0 ] doesn't make sense if $VAR is anything but a number. So you must avoid having that test evaluated in that case. Simply exchange your tests - || and && are short-circuiting (in bash at least, not sure if that's POSIX):

if [ "$VAR" = "*" ] || [ "$VAR" -gt 0 -a "$VAR" -lt 20 ] ; then

Upvotes: 1

Related Questions