| 1 | #!/bin/bash |
| 2 | # wr-ps.bash: while-read loop with process substitution. |
| 3 | |
| 4 | # This example contributed by Tomas Pospisek. |
| 5 | # (Heavily edited by the ABS Guide author.) |
| 6 | |
| 7 | echo |
| 8 | |
| 9 | echo "random input" | while read i |
| 10 | do |
| 11 | global=3D": Not available outside the loop." |
| 12 | # ... because it runs in a subshell. |
| 13 | done |
| 14 | |
| 15 | echo "\$global (from outside the subprocess) = $global" |
| 16 | # $global (from outside the subprocess) = |
| 17 | |
| 18 | echo; echo "--"; echo |
| 19 | |
| 20 | while read i |
| 21 | do |
| 22 | echo $i |
| 23 | global=3D": Available outside the loop." |
| 24 | # ... because it does NOT run in a subshell. |
| 25 | done < <( echo "random input" ) |
| 26 | # ^ ^ |
| 27 | |
| 28 | echo "\$global (using process substitution) = $global" |
| 29 | # Random input |
| 30 | # $global (using process substitution) = 3D: Available outside the loop. |
| 31 | |
| 32 | |
| 33 | echo; echo "##########"; echo |
| 34 | |
| 35 | |
| 36 | |
| 37 | # And likewise . . . |
| 38 | |
| 39 | declare -a inloop |
| 40 | index=0 |
| 41 | cat $0 | while read line |
| 42 | do |
| 43 | inloop[$index]="$line" |
| 44 | ((index++)) |
| 45 | # It runs in a subshell, so ... |
| 46 | done |
| 47 | echo "OUTPUT = " |
| 48 | echo ${inloop[*]} # ... nothing echoes. |
| 49 | |
| 50 | |
| 51 | echo; echo "--"; echo |
| 52 | |
| 53 | |
| 54 | declare -a outloop |
| 55 | index=0 |
| 56 | while read line |
| 57 | do |
| 58 | outloop[$index]="$line" |
| 59 | ((index++)) |
| 60 | # It does NOT run in a subshell, so ... |
| 61 | done < <( cat $0 ) |
| 62 | echo "OUTPUT = " |
| 63 | echo ${outloop[*]} # ... the entire script echoes. |
| 64 | |
| 65 | exit $? |