mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2318 (markdown)
34
SC2318.md
Normal file
34
SC2318.md
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
## This assignment is used again in this `declare`, but won't have taken effect. Use two `declare`s.
|
||||||
|
|
||||||
|
(or `local`, `typeset`, `readonly`, `export`)
|
||||||
|
|
||||||
|
### Problematic code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
declare -i first=$1 current=$first
|
||||||
|
```
|
||||||
|
|
||||||
|
### Correct code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
declare -i first=$1
|
||||||
|
declare -i current=$first
|
||||||
|
```
|
||||||
|
|
||||||
|
### Rationale:
|
||||||
|
|
||||||
|
When assigning variables via a command, such as `declare`, `typeset`, `local` etc, the expansion of all arguments happen before all assignments. This means that you can't have a variable assigned and then referenced in the same command.
|
||||||
|
|
||||||
|
In the example, if `$1` is 42, the arguments will first be expanded in the current environment into `-i first=42 current=`. They will then be passed to `declare` which will perform the assignments.
|
||||||
|
|
||||||
|
To correctly set `current=$first` so that it uses the new value of `first`, use two separate commands as shown.
|
||||||
|
|
||||||
|
Note that this only applies when assigning via commands, because arguments are always expanded before commands are invoked. If assigning without a command, as in `first=$1 current=$first`, it will work as expected.
|
||||||
|
|
||||||
|
### Exceptions:
|
||||||
|
|
||||||
|
If you want to reference the value as it existed before the command, e.g. if swapping variables with `declare x=$y y=$x`, you can ignore this message. However, consider rewriting it anyways for the benefit of any humans reading the code.
|
||||||
|
|
||||||
|
### Related resources:
|
||||||
|
|
||||||
|
* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!
|
Reference in New Issue
Block a user