From 55009f1da9d6b25d0260104ec8bb16db95d6446e Mon Sep 17 00:00:00 2001 From: Lucas Larson <91468+LucasLarson@users.noreply.github.com> Date: Sun, 8 May 2022 15:26:24 -0400 Subject: [PATCH] return the last argument passed to a function without resorting to bash --- SC3057.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/SC3057.md b/SC3057.md index ee289d3..b34967f 100644 --- a/SC3057.md +++ b/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!