mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC3057 (markdown)
35
SC3057.md
Normal file
35
SC3057.md
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
## In POSIX sh, string indexing is undefined.
|
||||||
|
|
||||||
|
(or "In dash, ... is not supported." when using `dash`)
|
||||||
|
|
||||||
|
### Problematic code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
#!/bin/sh
|
||||||
|
echo "Your initial is ${USER:0:1}"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Correct code:
|
||||||
|
|
||||||
|
Either switch to a shell that does support string indexing via parameter expansion, like `bash` or `ksh`, or rewrite with `cut`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
#!/bin/sh
|
||||||
|
echo "Your initial is $(printf '%s' "$USER" | cut -c 1)"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rationale:
|
||||||
|
|
||||||
|
String indexing is a bash and ksh extension, and does not work in `dash` or POSIX `sh`.
|
||||||
|
|
||||||
|
### Exceptions:
|
||||||
|
|
||||||
|
If you only intend to target shells that supports this feature, you can change
|
||||||
|
the shebang to a shell that guarantees support, or [[ignore]] this warning.
|
||||||
|
|
||||||
|
You can use `# shellcheck disable=SC3000-SC4000` to ignore all such compatibility
|
||||||
|
warnings.
|
||||||
|
|
||||||
|
### Related resources:
|
||||||
|
|
||||||
|
* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!
|
Reference in New Issue
Block a user