In this lesson, you will learn how to synchronize state between multiple independent shell sessions by using the filesystem as a shared "source of truth."
When you run two separate terminal windows, they don't share memory or variables. If you want Shell A to communicate a state change to Shell B, you cannot use environment variables or subshells, as those exist only within their own process boundaries. Instead, you can use the filesystem as a neutral ground where both processes can read and write data.
Atomic Operations: The Secret to Stability
When multiple processes try to update the same file simultaneously, you risk "race conditions," where data becomes garbled. To avoid this, we rely on atomic operations. An operation is atomic if it completes in its entirety or not at all, with no middle state visible to other processes.
In Linux, the mv (rename) command is a classic example of an atomic filesystem operation. Even if you are moving a large file, the actual rename within the same filesystem happens instantaneously from the perspective of other processes.
A Practical Example
Imagine you want to signal to another shell that a task is complete. You can use a temporary file to store the state:
# In Shell A: Create a status file
echo "completed" > task_status.tmp && mv task_status.tmp task_ready
# In Shell B: Poll for the state change
while [ ! -f task_ready ]; do
sleep 1
done
echo "Shell A has finished the task!"
By writing to a temporary file (.tmp) first and then moving it to the final destination (task_ready), Shell B will never see a "half-written" file. It will see either nothing, or the complete file once the move is finished. This pattern allows independent shell processes to coordinate complex workflows without needing to know about each other's internal memory or variable states. Because the filesystem is persistent and globally accessible to your user, it serves as the ultimate shared environment.
Key Takeaway: Use atomic operations, such as mv, to update shared state files, ensuring that other processes only ever see a complete, consistent version of your data.