exec Command Examples in Linux

The exec command is used to execute another command, replacing the current shell process with this new program’s process (no new process is created). This can be useful when you want to prevent the user from returning to the parent process if an error is encountered. For example, you may want to terminate a privileged shell if a command fails.

You can also use the exec command without a command as an argument to redirect all output in the shell to a file. This is commonly used in scripts to suppress stdout at the CLI and instead send it only to one or more files. For example:

#!/bin/bash
exec > out.txt
pwd
ls -al

The current working directory and directory listing will output to out.txt and not the CLI.

exec Command Examples

1. Replace with the specified command using the current environment variables:

# exec command -with -flags

2. Replace with the specified command, clearing environment variables:

# exec -c command -with -flags

3. Replace with the specified command and login using the default shell:

# exec -l command -with -flags

4. Replace with the specified command and change the process name:

# exec -a process_name command -with -flags
Related Post