Bash – What Does an ‘exec’ Command Do?

bash

I don't understand the bash command exec. I have seen it used inside scripts to redirect all output to a file (as seen in this). But I don't understand how it works or what it does in general. I have read the man pages but I don't understand them.

Best Answer

man bash says:

exec [-cl] [-a name] [command [arguments]]
      If command is specified, it replaces the shell.  No new  process
      is  created.  The arguments become the arguments to command.  If
      the -l option is supplied,  the  shell  places  a  dash  at  the
      beginning  of  the  zeroth  argument passed to command.  This is
      what login(1) does.  The -c option causes command to be executed
      with  an empty environment.  If -a is supplied, the shell passes
      name as the zeroth argument to the executed command.  If command
      cannot  be  executed  for  some  reason, a non-interactive shell
      exits, unless the execfail shell option  is  enabled.   In  that
      case,  it returns failure.  An interactive shell returns failure
      if the file cannot be executed.  If command  is  not  specified,
      any  redirections  take  effect  in  the  current shell, and the
      return status is 0.  If there is a redirection error, the return
      status is 1.

The last two lines are what is important: If you run exec by itself, without a command, it will simply make the redirections apply to the current shell. You probably know that when you run command > file, the output of command is written to file instead of to your terminal (this is called a redirection). If you run exec > file instead, then the redirection applies to the entire shell: Any output produced by the shell is written to file instead of to your terminal. For example here

bash-3.2$ bash
bash-3.2$ exec > file
bash-3.2$ date
bash-3.2$ exit
bash-3.2$ cat file
Thu 18 Sep 2014 23:56:25 CEST

I first start a new bash shell. Then, in this new shell I run exec > file, so that all output is redirected to file. Indeed, after that I run date but I get no output, because the output is redirected to file. Then I exit my shell (so that the redirection no longer applies) and I see that file indeed contains the output of the date command I ran earlier.