exec: Linux Command and Unix Command

Redirect shell output, or launch a new program with the current PID

In Linux, the exec command replaces the current shell process with a specified command—in essence, transferring the current shell's process ID to a new process, which then assumes that PID.

Most casual desktop Linux users shouldn't use exec. It's a powerful program with a narrow use case for scripting. In normal circumstances, there's rarely a value to invoking exec for routine shell operations.

How 'exec' Works

When you run exec with a new command as an argument, Linux runs that new command using the same process as the shell that invoked it. If you run it without specifying a new command, then relevant redirections take place in the current shell.

For example, when you launch a shell session by starting a terminal-management program, the default shell automatically invokes. When you type exit, the shell session terminates, and, depending on the terminal-management software, the window may vanish.

To see how exec works, launch a shell, then launch a second shell in the same session. If you use Zsh, for example, then when the terminal window opens, launch another Zsh session.

multiple shells

When you check the running process, you'll see that each time you invoke the shell, a new job with a separate process ID spawns. And every time you exit a shell session with the exit command, one of those sessions terminates.

If you execute date from a shell session, you'll see the date displayed to standard output. If you then use exec to redirect standard output to a text file, the standard output you expect to see writes to the file, until you exit the Zsh session that exec controls. When you exit, the standard output displays as expected because the original Zsh session becomes active again.

linux exec command

Use Case for 'exec'

One common use case for exec relates to tidying up a script. If you need to use a script to tee up the parameters for a command, then terminating the script with exec launches the new program with those parameters and closes the current shell session.

Was this page helpful?