2

I'm learning echo command:

$ echo $100
00
$ echo $1

$

so why does echo parse $1 as undefined variable and print following zeros but not $100 as a whole? I'm using Ubuntu 14.04.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
mzoz
  • 155

1 Answers1

2

The positional parameters, $1, $2, ..., $9, contain the command line arguments passed to the current shell or shell function. The string $100 will be interpreted as $1 followed by two zeroes. This will be 00 if $1 is unset or empty.

Setting the three first positional parameters explicitly in a script and testing it:

set -- a b c

echo "$100 $200 $300"

This results in the output

a00 b00 c00

Since the positional parameters beyond 9 need to be accessed with e.g. ${10}, there is no ambiguity between $1 followed by 00 and "positional parameter 10 or 100" (since there are no brackets).

If you had wanted to print the literal string $100, then you would have to either escape the $ from the shell, or use single quotes:

echo \$100
echo '$100'
Kusalananda
  • 333,661
  • bash(1) is clear on this: "A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell's arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameters may not be assigned to with assignment statements. The positional parameters are temporarily replaced when a shell function is executed (see FUNCTIONS below). When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces (see EXPANSION below)." – Fox Aug 21 '17 at 15:10