Exec command

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Compound commandHomeChapter 8 Challenges →

Use exec command to replace the shell with the given command. The exec command is used to replace the current shell with the command without spawning a new process or subshell. The exec command is also used to assign the file descriptor fd to filename:

exec 3> /tmp/output

exec command syntax

The syntax is:

exec [-cl] [-a name] [command [arguments ...]] [redirection ...]

Options:

  1. -a name : pass NAME as the zeroth argument to COMMAND
  2. -c  : execute COMMAND with an empty environment
  3. -l  : place a dash in the zeroth argument to COMMAND

exec command examples

Let us see some examples of the exec command.

ssh-agent command

Start ssh-agent as follows:

exec ssh-agent $SHELL

Next adds private key identities to the authentication agent:

ssh-add
ssh-agen with exec command

Wrapper script

The exec command is used by "wrapper" scripts. For example, php-cgi can run as cgi program after setting environment variables or other configuration. By using exec, the resources used by the php.cgi shell program do not need to stay in use after the program is started. The following script can be run using Apache web server and it will speed up php execution:

#!/bin/bash
# Shell Script wrapper to Run PHP5 using mod_fastcgi under Apache 2.2.x
# Tested under CentOS Linux and FreeBSD and 7.x server.
PHP_CGI=/usr/local/bin/php-cgi
# for centos / rhel set it as follows
# PHP_CGI=/usr/bin/php-cgi
export PHP_FCGI_CHILDREN=4
export PHP_FCGI_MAX_REQUESTS=1000
exec $PHP_CGI
← Compound commandHomeChapter 8 Challenges →