return the last argument passed to a function without resorting to bash

Lucas Larson
2022-05-08 15:26:24 -04:00
parent f83e8272fe
commit 55009f1da9

@@ -18,6 +18,16 @@ Either switch to a shell that does support string indexing via parameter expansi
echo "Your initial is $(printf '%s' "$USER" | cut -c 1)"
```
To find the last argument passed to a shell script without using bashs `${@:$#}`- or `${@: -1}`-style string indexing, use the following, which even “[works in the unix v7 bourne shell from 1979](https://stackoverflow.com/q/1853946#comment104235724_1853993)”:
```sh
#!/bin/sh
for argument in "$@"; do
: # `:`, also called as `true`, is a no-op here
done
printf '%s\n' "${argument-}"
```
### Rationale:
String indexing is a bash and ksh extension, and does not work in `dash` or POSIX `sh`.
@@ -31,5 +41,6 @@ You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibilit
warnings.
### Related resources:
[^1]:
* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!