Add alternative using a delimiting character instead of string indexing

immeëmosol
2025-07-19 00:25:36 +00:00
parent 4bf34df21d
commit 662733073e

@@ -28,6 +28,25 @@ done
printf '%s\n' "${argument-}" printf '%s\n' "${argument-}"
``` ```
An alternative could be to use a delimiting character instead. For instance, to use texts prefixed with a number, an option is to use a colon as a delimiter and use that in a parameter expansion that removes a pattern form either beginning or ending of variable value:
```sh
#!/bin/sh
exitForReasonX='4:Stopping %s because of X.'
exitForReasonY='6:Stopping because of Y.'
echo "The ''reason y'' has number '${exitForReasonY#*:}' and its message is: '${exitForReasonY%%:*}'."
# A more useful example might be :
reasonableExit ()
{
state="${1:-}"
state="${state:?is required}"
${1+shift}
>&2 printf '%s\n' "${state%%:*}" ${1+"${@?}"}
exit "${state#*:}"
}
reasonableExit "${exitForReasonX?}" 'something'
```
### Rationale: ### Rationale:
String indexing is a bash and ksh extension, and does not work in `dash` or POSIX `sh`. String indexing is a bash and ksh extension, and does not work in `dash` or POSIX `sh`.