Updated SC2308 (markdown)

Eisuke Kawashima
2025-07-29 10:38:15 +09:00
parent 5c9f6c8244
commit 4daacaa809

@@ -39,6 +39,7 @@ col2="${str:7:5}"
# Get substring by index (POSIX)
col2="$(printf 'foo bar baz\n' | cut -c 8-12)"
```
### Rationale:
You are using a `expr` with `length`, `match`, `index`, or `substr`. These forms did not make it into POSIX, and fail on platforms like MacOS and FreeBSD. Consider replacing them with portable equivalents:
@@ -52,7 +53,7 @@ can be trivially replaced with the POSIX form `expr str : regex`
#### `index`
if you only need a numerical index as part of trying to extract a piece of the string, consider replacing it with parameter expansion:
```
```sh
str="mykey=myvalue"
key="${str%%=*}" # Remove everything after first =, no index required
value="${str#*=}" # Remove everything before first =, no index required
@@ -60,7 +61,7 @@ value="${str#*=}" # Remove everything before first =, no index required
otherwise, you can find the index of the first `=` using parameter expansion and string length:
```
```sh
str="mykey=myvalue"
x=${str%%=*} # Assign x="mystr"
index=$((${#x}+1)) # Add 1 to length of x
@@ -70,14 +71,14 @@ index=$((${#x}+1)) # Add 1 to length of x
Extract a substring via character index is generally fragile. For example, in this example, any minor changes to the format, including just the version increasing from 8.9 to 8.10, will cause the following snippet to fail:
```
```sh
str="VIM - Vi IMproved 8.2 (2019 Dec 12, compiled Feb 15 2021 12:29:39)"
version=$(expr substr "$str" 19 3)
```
Instead, consider a different approach:
```
```sh
x="${str%% (*}" # Delete ` (` and everything after, giving "VIM - Vi IMproved 8.2"
version="${x##* }" # Delete everything before last space, giving "8.2"