Subshells and Process Forking
Subshells and Process Forking
A subshell is a separate child process spawned by the current shell that inherits environment variables, open file descriptors, and shell options, but cannot modify the parent shell’s memory space.
When Subshells Are Created
- Parentheses grouping:
( cd /tmp && rm -rf build ) - Command substitution:
output=$(grep "ERROR" /var/log/syslog) - Pipelines:
cat file.txt | while read -r line; do count=$((count+1)); done
The Pipeline Subshell Trap
count=0
cat << 'EOF' > test.txt
alpha
beta
gamma
EOF
# In standard Bash, every component of a pipeline executes in a subshell!
cat test.txt | while read -r line; do
count=$((count + 1))
done
echo "Final Count: $count"
# Output: Final Count: 0 (The parent count was never modified!)
# Solution 1: Process Substitution
count=0
while read -r line; do
count=$((count + 1))
done < <(cat test.txt)
echo "Final Count: $count" # Output: 3
# Solution 2: Enable lastpipe in non-interactive scripts
shopt -s lastpipe
set +m
cat test.txt | while read -r line; do count=$((count + 1)); done
echo "Final Count: $count" # Output: 3