Bash reads and executes scripts line by line (or more precisely, command by command) rather than loading the entire script into memory at once. This means that bash maintains a file handle to the script and reads from it as execution progresses.
This behavior has an important implication: if you modify a script file while it's running, those changes can indeed affect the execution. When bash reaches a line it hasn't read yet, it will read the modified version from disk.
Here's a simple demonstration:
#!/bin/bash
echo "Line 1"
sleep 5
echo "Line 2"
echo "Line 3"
If you run this script and quickly modify it during the 5-second sleep (for example, changing "Line 3" to "Modified Line 3"), you'll see the modified output when execution reaches that line.
However, there are some nuances:
-
Buffering: Bash does some internal buffering for efficiency, so it might read slightly ahead of the current execution point. This means very small scripts might be fully buffered.
-
Functions and loops: When bash encounters a function definition or a loop, it must read the entire construct before executing it. These structures are parsed completely and stored in memory.
-
Source command: When you use source or . to include another script, that script is also read progressively.
This line-by-line reading behavior can lead to unexpected results if scripts are modified during execution, which is why it's generally considered bad practice to modify a running script. If you need to ensure a script runs with consistent content, you might consider:
- Copying the script to a temporary location before execution
- Using file locking mechanisms
- Designing your deployment process to avoid modifying running scripts