27.08.2015 Views

Advanced Bash−Scripting Guide

Advanced Bash-Scripting Guide - Nicku.org

Advanced Bash-Scripting Guide - Nicku.org

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Advanced</strong> <strong>Bash−Scripting</strong> <strong>Guide</strong><br />

This shell builtin replaces the current process with a specified command. Normally, when the shell<br />

encounters a command, it forks off a child process to actually execute the command. Using the exec<br />

builtin, the shell does not fork, and the command exec'ed replaces the shell. When used in a script,<br />

therefore, it forces an exit from the script when the exec'ed command terminates. For this reason, if an<br />

exec appears in a script, it would probably be the final command.<br />

Example 11−20. Effects of exec<br />

#!/bin/bash<br />

exec echo "Exiting \"$0\"."<br />

# Exit from script here.<br />

# −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−<br />

# The following lines never execute.<br />

echo "This echo will never echo."<br />

exit 99<br />

# This script will not exit here.<br />

# Check exit value after script terminates<br />

#+ with an 'echo $?'.<br />

# It will *not* be 99.<br />

Example 11−21. A script that exec's itself<br />

#!/bin/bash<br />

# self−exec.sh<br />

echo<br />

echo "This line appears ONCE in the script, yet it keeps echoing."<br />

echo "The PID of this instance of the script is still $$."<br />

# Demonstrates that a subshell is not forked off.<br />

echo "==================== Hit Ctl−C to exit ===================="<br />

sleep 1<br />

exec $0<br />

# Spawns another instance of this same script<br />

#+ that replaces the previous one.<br />

echo "This line will never echo!" # Why not?<br />

exit 0<br />

An exec also serves to reassign file descriptors. exec

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!