Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux Bash's rule for determing a variable name Greedy or Non-Greedy

If you run the following bash script on Ubuntu 12.04:

t="t"
echo "1st Output this $15"
echo "2nd this $test"

The output is:

1st Output this 5
2nd this

How can the first echo takes $1 as a variable name (non-greedy) interpreting it as ${1}5 while the second echo takes $test as a variable name (greedy) instead of interpreting it as ${t}est?

like image 756
James King Avatar asked Mar 08 '26 03:03

James King


1 Answers

There are two parts to your question:

  • $15 would always be interpreted as $1, i.e. the first positional parameter1, concatenated with 5. In order to use the fifteenth positional parameter, you'd need to say ${15}.

  • $test would be interpreted as variable test. So if you want it to be interpreted as $t concatenated with est, then you need to say ${t}est

1Quoting from info bash:

   When  a  positional parameter consisting of more than a single digit is
   expanded, it must be enclosed in braces (see EXPANSION below).

   ...

EXPANSION
   Expansion is performed on the command line after it has been split into
   words.  There are seven kinds of expansion performed: brace  expansion,
   tilde  expansion,  parameter  and variable expansion, command substitu‐
   tion, arithmetic expansion, word splitting, and pathname expansion.

You may also want to refer to:

  • What's the difference between ${varname} and $varname in a shell scripts
like image 71
devnull Avatar answered Mar 09 '26 17:03

devnull