diff --git a/SC2031.md b/SC2031.md index 61854a1..7dbcc62 100644 --- a/SC2031.md +++ b/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: