In this lesson, you will learn how to safely pass complex data structures, like associative arrays, from a parent shell to a child process.
The Challenge of Isolation
In Linux, every shell script runs in its own isolated memory space. When you spawn a child process—for instance, by calling a subshell or a background job—that child inherits the parent's environment variables, but it does not inherit complex objects like associative arrays or dynamically populated arrays. If you try to access an associative array in a subshell that was defined in the parent, you will find it empty.
Serialization as a Bridge
To overcome this isolation, we use serialization. We convert our complex data into a structured string format (like a flat string representation of keys and values) that the child can "de-serialize" or parse back into its own local memory.
Consider this scenario where we pass an associative array to a background process using a delimiter-aware string:
declare -A my_data=( [cpu]="high" [mem]="low" )
# Serialize: Convert keys/values into a delimited string
serialized_data=""
for key in "${!my_data[@]}"; do
serialized_data+="$key=${my_data[$key]}|"
done
# Pass the string to a child process
(
IFS='|' read -ra pairs <<< "$serialized_data"
declare -A child_data
for pair in "${pairs[@]}"; do
key="${pair%%=*}"
val="${pair#*=}"
child_data[$key]="$val"
done
echo "Child sees CPU: ${child_data[cpu]}"
)
Why This Matters
By "flattening" our data, we bridge the memory gap between independent processes. We treat the data as a stream of text, which is the universal language of Linux IPC (Inter-Process Communication). When your script grows to handle stateful loops or complex configurations, serializing your data into pipes or environment-passed strings ensures that your child tasks remain synchronized with the parent's intent without risking data corruption or empty variable errors.
Key Takeaway: Since subshells cannot inherit complex memory structures directly, you must serialize your data into a string format to safely transfer it across process boundaries.