exec - Linux Command - Unix Command

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

man using laptop

Peopleimages / E+ / Getty Images

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 aficionados 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 your terminal-managment program, your default shell automatically invokes. If you type exit, the shell session terminates and, depending on your terminal-management software, the window may vanish, too.

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

multiple shells

When you check the running process, you'll see that each time you invoke your shell, a new job with its own process ID spawns. And every time you exit a shell session with the exit command, one of those sessions terminates—like a series of nested Russian dolls.

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, then all the standard output you'd expect to see actually writes to the file, until you exit the Zsh session that exec controls. When you exit, then 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.