*Tags*: cmd:case
Date: 1999-08-24
> > > case "$VAR" in > > Heck, with case you don't even need the quotes: > > case $VAR in > > YES) ... ;; > > esac > > Hrrrmm... what if it's possible that the expansion will result in an > empty string? Wouldn't quotes be the safe way to go "just in case?"
It is definitely safe to add them, but the case statement will still work correctly even if the variable does expand to an empty string:
$ v= $ case $v in "") echo empty;; *) echo not empty ;; esac empty $ v=in $ case $v in "") echo empty;; *) echo not empty ;; esac not empty $ case $v in *\ *) echo has space ;; *) echo no space ;; esac no space $ v="foo bar" $ case $v in *\ *) echo has space ;; *) echo no space ;; esac has space $ v="foo*bar" $ case $v in *\**) echo has star ;; *) echo no star ;; esac has star
There is certainly nothing wrong with adding double-quotes around a variable expansion which is used as the word-to-be-cased in the case statement, I was merely pointing out that it is an additional benefit of using case (instead of test) that the quotes are not _required_.
Ken Pizzini
Variables are expanded for command execution. case is a keyword, while test "[ condition ]" is a builtin command. So in a test statement, variable expansion occurs. That is one of the reasons to use conditional expressions in ksh, the posix shell and bash: "[[" is a keyword, so variable and filename expansion do not occur.
For instance:
if [[ $VAR = xyz ]]
works for all values of $VAR. Note, it doesn't require quoting. However, the RHS may require quoting:
if [[ $VAR = "$xyz" ]]
And
if [[ $VAR = *xyz* ]]
is true if VAR contains the string or substring "xyz". If you tried that with test, *xyz* would expand to filenames containing the string xyz, or the literal pattern "*xyz*".
Dan Mercer