mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 11:19:45 +08:00
Created SC2178 (markdown)
41
SC2178.md
Normal file
41
SC2178.md
Normal file
@@ -0,0 +1,41 @@
|
||||
## Variable was used as an array but is now assigned a string.
|
||||
|
||||
### Problematic code:
|
||||
|
||||
```sh
|
||||
flags[0]="-r"
|
||||
flags[1]="--delete-after"
|
||||
|
||||
if [ "$dryrun" ]
|
||||
then
|
||||
flags="--dry-run"
|
||||
fi
|
||||
|
||||
```
|
||||
|
||||
### Correct code:
|
||||
|
||||
```sh
|
||||
flags[0]="-r"
|
||||
flags[1]="--delete-after"
|
||||
|
||||
if [ "$dryrun" ]
|
||||
then
|
||||
flags=( "--dry-run" )
|
||||
fi
|
||||
```
|
||||
### Rationale:
|
||||
|
||||
ShellCheck noticed that you have used a variable as an array, but then assign it a string. `array=foo` is equivalent to `array[0]=foo`, and leaves the rest of the elements unaffected.
|
||||
|
||||
In the incorrect code, `"${flags[@]}"` would contain `--dry-run` `--delete-after`.
|
||||
|
||||
To set an array to only a single, given element, you should use `array=( foo )`.
|
||||
|
||||
In the correct code, `"${flags[@]}"` will contain `--dry-run` only.
|
||||
|
||||
Another possible cause is accidentally missing the `$` on a previous assignment: `var=(my command); var=bar` instead of `var=$(my command); var=bar`. If the variable is not intended to be an array, ensure that it's never assigned as one.
|
||||
|
||||
### Exceptions:
|
||||
|
||||
ShellCheck can get confused by variable scope if the same variable name was used as an array previously, but is a string in the current context. You can [[ignore]] it in this case.
|
Reference in New Issue
Block a user