From 4d7333cb68bdf52bb948c09880eb54001e12d46b Mon Sep 17 00:00:00 2001 From: Mingye Wang Date: Wed, 30 Sep 2015 09:37:05 -0400 Subject: [PATCH] Updated SC2031 (markdown) --- SC2031.md | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) 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: