18

While trying to get last positional parameter set in /bin/dash , I've tried echo ${$#}. Surprisingly this did not result in an error, but into PID which is the same as $$ variable contents. Question, is why did that syntax work ? What is the syntax rule that shell applied here ?

Basically, what I did is

$ set 1 2 3 4 5
$ echo ${$#}
13819
$ echo $$
13819

Apparently, % character also get ignored in such construct

$ echo ${$%}
13819

But * and @ result in bad substitution error:

$ echo ${$*}
sh: 10: Bad substitution
$ echo ${$@}
sh: 11: Bad substitution
  • 3
    What are you expecting ${$*} and ${$@} to produce? – Kusalananda Feb 13 at 7:34
  • 2
    @Kusalananda No expectations. I was trying other characters beside # and % and what behavior results from those. – Sergiy Kolodyazhnyy Feb 13 at 7:36
  • 1
    To actually do indirection in Dash, use eval, e.g. dash -c 'set 1 2 3 4 5; eval "echo \$$#"'. Source: Ubuntu Wiki – wjandrea Feb 13 at 20:09
  • 1
    @wjandrea Yep, already aware of that one. There's actually already a question about it: stackoverflow.com/questions/1853946/… I was trying to find a method by myself without reading the question first ( and I already knew for i; do true; done to get last item into $i ) but was looking for something more elegant. eval of course can have potential issues, thought to what extent - that's another topic. But yes, it's an option – Sergiy Kolodyazhnyy Feb 13 at 20:18
35

This is $$ with an empty prefix removed:

${parameter#[word]}

Remove Smallest Prefix Pattern. The word shall be expanded to produce a pattern. The parameter expansion shall then result in parameter, with the smallest portion of the prefix matched by the pattern deleted. If present, word shall not begin with an unquoted #.

The same applies for % (suffix). @ and * are not parameter expansion modifiers, so they are errors. It would happen for $?, $-, or a hypothetical $= as well. ${$+} is an empty expansion.

  • I should have recognized parameter substitution immediately there. Good catch. – Sergiy Kolodyazhnyy Feb 13 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.