mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Expanded on how to use lastpipe
16
SC2031.md
16
SC2031.md
@@ -18,9 +18,19 @@ n=0
|
|||||||
while read i; do (( n+=i )); done < <(printf "%s\n" {1..10})
|
while read i; do (( n+=i )); done < <(printf "%s\n" {1..10})
|
||||||
echo $n
|
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.
|
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:
|
### 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).
|
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:
|
Pipelines:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
subshell1 | subshell2 | subshell3 # Bash, Dash, Ash
|
subshell1 | subshell2 | subshell3 # Dash, Ash, Bash (default)
|
||||||
subshell1 | subshell2 | regular # Ksh, Zsh
|
subshell1 | subshell2 | regular # Ksh, Zsh, Bash (with lastpipe=on and no job control)
|
||||||
```
|
```
|
||||||
|
|
||||||
Command substitution:
|
Command substitution:
|
||||||
|
Reference in New Issue
Block a user