Debian Codegraph @

avoid-subshell.sh

raw symbols SCIP
1 #!/bin/bash
2 # avoid-subshell.sh
3 # Suggested by Matthew Walker.
4
5 Lines=0
6
7 echo
8
9 cat myfile.txt | while read line;
10 do {
11 echo $line
12 (( Lines++ )); # Incremented values of this variable
13 #+ inaccessible outside loop.
14 # Subshell problem.
15 }
16 done
17
18 echo "Number of lines read = $Lines" # 0
19 # Wrong!
20
21 echo "------------------------"
22
23
24 exec 3<> myfile.txt
25 while read line <&3
26 do {
27 echo "$line"
28 (( Lines++ )); # Incremented values of this variable
29 #+ accessible outside loop.
30 # No subshell, no problem.
31 }
32 done
33 exec 3>&-
34
35 echo "Number of lines read = $Lines" # 8
36
37 echo
38
39 exit 0
40
41 # Lines below not seen by script.
42
43 $ cat myfile.txt
44
45 Line 1.
46 Line 2.
47 Line 3.
48 Line 4.
49 Line 5.
50 Line 6.
51 Line 7.
52 Line 8.