What Does exec Do in Bash Scripts? A Hands‑On Exploration
This article explains the purpose of the Bash built‑in exec command, demonstrates its effect on process trees through step‑by‑step experiments, and highlights important cautions when using exec in shell scripts.
0x01 Example
In a typical shell script you would write a command directly, such as sleep 10. The article shows a script where the command is preceded by exec, illustrated by the following screenshot.
0x02 The Role of exec
The built‑in exec replaces the current shell process with the specified program. Using help exec in Bash displays a brief description, which the article reproduces and notes that the wording is vague.
0x03 Experiments
First, the script runs without exec. After execution, ps shows a process tree where the sleep process is a child of the script, and the script is a child of the interactive Bash.
Next, the script is modified to prepend exec to the sleep command. Running it again produces a different process tree: the script process disappears because it has been replaced by the sleep program.
This demonstrates that exec tells the Linux kernel to load and run the target program directly in the current shell process, overwriting the original script's code and data, and causing the original process to terminate immediately.
0x04 Precautions
Because exec replaces the current process, any commands placed after it (except error‑handling logic) will never be executed. The article shows an example where exec echo hello is followed by echo world; only "hello" is printed.
For deeper understanding, readers are directed to the execve manual page, which documents the underlying system call used by the exec built‑in.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
