0

So this snippet of code works just fine, the "$i" is in double quotes:

for ((i=0; i <= 10; i++)); do
    printf '%d\n' "$i"
    done

However, if I put the "$i" in single quotes ('$i'), i just get 10 iterations of this:

bash: printf: $i: invalid number
0

Why? This question contains a bug report, it's not philosophical like the question everyone is saying it's exactly like. I can't read everything on the internet before determining that it was a "bad question".

muru
  • 72,889

1 Answers1

5

When you wrap a string in single-quotes, the shell will not perform variable expansion on the string. You get the literal string. In the case of your printf command, the value $i is not a valid decimal number, so printf encounters an error.

When you wrap a string in double-quotes, the shell will perform variable expansion on it, which in your case, returns the value of the integer in the i variable, and printf is happy with it.

Sotto Voce
  • 4,131
  • It's worth noting that %d\n is crucial for the error to appear. If it was %s\n, then printf would be happy either way. More: the OP would see what the tool got from "$i" or '$i'. – Kamil Maciorowski Aug 11 '22 at 09:35
  • Yes, however the error message shows that printf saw $i rather than 0, 1, 2, etc., and the error points out that the problem with $i is that it's not a number. Humans often aren't literal-minded enough to understand the errors that our programs display to us. – Sotto Voce Aug 11 '22 at 10:23