mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
return the last argument passed to a function without resorting to bash
11
SC3057.md
11
SC3057.md
@@ -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 bash’s `${@:$#}`- 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!
|
||||
|
Reference in New Issue
Block a user