kvantour
kvantour

Reputation: 26491

Is there a syntactical difference between single and double quoted empty strings?

According to the bash manual, there is no syntactical difference. The bash-parser on the other hand seems to have a different opinion on that when dealing with arithmetic expressions:

$ echo "$BASH_VERSION"
5.2.15(1)-release
$ echo $((""))
0
$ echo $((''))
bash: '': syntax error: operand expected (error token is "''")

Related:

Upvotes: 3

Views: 290

Answers (3)

kvantour
kvantour

Reputation: 26491

There seems to be a subtle difference introduced in Bash 5.2. The manual states:

(( expression ))

The arithmetic expression is evaluated according to the rules described below (see Shell Arithmetic). The expression undergoes the same expansions as if it were within double quotes, but double quote characters in expression are not treated specially and are removed. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1.

Source: Bash Reference Manual: Section Conditional Constructs

This implies that (("")) is equivalent to (()) but (('')) is a syntactical error as single quotes are not removed from expression.

Upvotes: 4

Léa Gris
Léa Gris

Reputation: 19625

Exploring how different shell brands handles this

  • bash version 5.1-6
  • dash version 0.5.11
  • ksh93 version 1.0.0~beta.2
  • zsh version 5.8.1

Ksh93 seems to show the most distinctive behavior.

What it teaches is:

Within an arithmetic context, shells interpret a single quote as the single quote character itself, but not as the quoted literal value.

#!/usr/bin/env sh

for shell in bash dash ksh93 zsh; do
  printf 'Testing with %s:\n' "$shell"
  "$shell" <<'EOF'
LC_ALL=C
echo "$((''))"
EOF
  echo
done

Output:

Testing with bash:
bash: line 2: '': syntax error: operand expected (error token is "''")

Testing with dash:
ash: 2: arithmetic expression: expecting primary: "''"

Testing with ksh93:
39

Testing with zsh:
zsh: bad math expression: illegal character: '

Upvotes: 3

choroba
choroba

Reputation: 241988

Seems like a bug, as the manual says

All tokens in the expression undergo parameter and variable expansion, command substitution, and quote removal.

Upvotes: 2

Related Questions