From a8777bb375377ce0dc751ad14cc63ad194eefccb Mon Sep 17 00:00:00 2001 From: Grische Date: Thu, 18 Nov 2021 16:58:33 +0100 Subject: [PATCH] Expanded on how to use lastpipe --- SC2031.md | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/SC2031.md b/SC2031.md index a70380d..50c28cf 100644 --- a/SC2031.md +++ b/SC2031.md @@ -18,9 +18,19 @@ n=0 while read i; do (( n+=i )); done < <(printf "%s\n" {1..10}) echo $n ``` - 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. + +With Bash 4.2+ you can also use `shopt -s lastpipe` which will change the pipe behaviour to be similar to Ksh and Zsh (see Rationale below) [as long as job control is not active](https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html) (e.g. inside a script): +```bash +#!/usr/bin/env bash +shopt -s lastpipe +n=0 +printf "%s\n" {1..10} | while read i; do (( n+=i )); done +echo $n +``` + + ### Rationale: Variables set in subshells are not available outside the subshell. This is a wide topic, and better described on the [Wooledge Bash Wiki](http://mywiki.wooledge.org/BashFAQ/024). @@ -30,8 +40,8 @@ Here are some constructs that cause subshells (shellcheck may not warn about all Pipelines: ```sh -subshell1 | subshell2 | subshell3 # Bash, Dash, Ash -subshell1 | subshell2 | regular # Ksh, Zsh +subshell1 | subshell2 | subshell3 # Dash, Ash, Bash (default) +subshell1 | subshell2 | regular # Ksh, Zsh, Bash (with lastpipe=on and no job control) ``` Command substitution: