Home > Blockchain >  /bin/sh alternative to ${!#} in /bin/bash
/bin/sh alternative to ${!#} in /bin/bash

Time:08-19

I'm trying to understand what is the alternative of ${!#} of /bin/bash on /bin/sh?

I know that ${!#}, which evaluated to ${0} on /bin/bash but how can I get it using /bin/sh?

CodePudding user response:

The closest approximation you can get in sh is an eval-based solution.

eval echo "\$${#}"

But keep in mind that eval is very dangerous if not used carefully. I'd recommend considering if you need indirection or not before implementing.

For example, the above code basically reduces to "print the last argument." You could write this without using indirection or eval:

for arg in "${0}" "${@}" ; do
:
done
echo "${arg}"

CodePudding user response:

There is nothing wrong with using eval in this case.

You should wrap $# in curly braces though; otherwise it won't work when the number of positional parameters exceeds nine. See:

$ set -- a b c d e f g h i j
$ eval "arg=\$$#"
$ echo "$arg"
a0
$
$ eval "arg=\${$#}"
$ echo "$arg"
j
  • Related