Pages

Thursday, 17 June 2021

foo=hello; echo $foo_1

Problem

 $ foo=hello; echo $foo_1

 $

The above command will print an empty line.

Reason

When resolving a variable, bash uses the longest possible string as the variable's name. e.g.

$ foo=hello; foobar=bye; echo $foobar  # foobar is selected
bye
$ foo=hello; foobar=bye; echo $foob    # foob is selected but not defined
$ foo=hello; foobar=bye; echo $foo-bar # foo is selected as "-" is not allowed in a variable name.
hello-bar

$ foo=hello; foobar=bye; echo $foo_bar # foo_bar is selected as "_" is allowed in a vairable name. As foo_bar is not defined, it printed empty line.

Solution

Braces!

$ foo=hello; echo ${foo}_txt
hello_txt
$ foo=hello; echo ${foo}world
helloworld

Good to know

Legal letters for a variable name include [A-Z], [a-z], [0-9], and _.


No comments:

Post a Comment