mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Updated SC2031 (markdown)
20
SC2031.md
20
SC2031.md
@@ -4,18 +4,22 @@
|
||||
|
||||
There are many ways of accidentally creating subshells, but a common one is piping to a loop:
|
||||
|
||||
n=0
|
||||
printf "%s\n" {1..10} | while read i; do (( n+=i )); done
|
||||
echo $n
|
||||
```bash
|
||||
n=0
|
||||
printf "%s\n" {1..10} | while read i; do (( n+=i )); done
|
||||
echo $n
|
||||
```
|
||||
|
||||
### Correct code:
|
||||
|
||||
# Bash specific:
|
||||
n=0
|
||||
while read i; do (( n+=i )); done < <(printf "%s\n" {1..10})
|
||||
echo $n
|
||||
```bash
|
||||
# Bash specific: process substitution. Also try shopts like lastpipe.
|
||||
n=0
|
||||
while read i; do (( n+=i )); done < <(printf "%s\n" {1..10})
|
||||
echo $n
|
||||
```
|
||||
|
||||
In `sh`, a temp file can be used instead of process substitution.
|
||||
In `sh`, a temp file (better if fifo or fd) can be used instead of process substitution. And if it's acceptable to do it with waiting, try Here Documents.
|
||||
|
||||
### Rationale:
|
||||
|
||||
|
Reference in New Issue
Block a user