mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2316 (markdown)
42
SC2316.md
Normal file
42
SC2316.md
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
## This applies local to the variable named readonly, which is probably not what you want. Use a separate command or the appropriate `declare` options instead.
|
||||||
|
|
||||||
|
|
||||||
|
### Problematic code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
local readonly foo=3
|
||||||
|
readonly export bar=4
|
||||||
|
```
|
||||||
|
|
||||||
|
### Correct code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
local foo=3
|
||||||
|
readonly foo
|
||||||
|
|
||||||
|
readonly bar=4
|
||||||
|
export bar
|
||||||
|
```
|
||||||
|
|
||||||
|
or
|
||||||
|
|
||||||
|
```
|
||||||
|
declare -r foo=3
|
||||||
|
declare -rx bar=4
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rationale:
|
||||||
|
|
||||||
|
In most languages, declaration modifiers like `public`/`static`/`const` are keywords and you can apply multiple to any declaration.
|
||||||
|
|
||||||
|
In shell scripting they are instead command names, and anything after them is an argument. This means that `readonly local foo` will create two readonly variables: `local`, and `foo`. Neither will be local.
|
||||||
|
|
||||||
|
Instead, either use multiple commands, or use a single `declare` command with appropriate flags (`declare` will automatically make a variable local when invoked in a function, unless `-g` is passed to explicitly make it global).
|
||||||
|
|
||||||
|
### Exceptions:
|
||||||
|
|
||||||
|
If you want to name your variable `local`, you can quote it as in `readonly "local"` to make your intention clear to ShellCheck and other humans.
|
||||||
|
|
||||||
|
### Related resources:
|
||||||
|
|
||||||
|
* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!
|
Reference in New Issue
Block a user