mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 11:19:45 +08:00
Add alternative using a delimiting character instead of string indexing
19
SC3057.md
19
SC3057.md
@@ -28,6 +28,25 @@ done
|
||||
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:
|
||||
|
||||
String indexing is a bash and ksh extension, and does not work in `dash` or POSIX `sh`.
|
||||
|
Reference in New Issue
Block a user