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.
If you encounter the below error while running the exec command:
exec: command not found
you may try installing the below package as per your choice of distribution:
OS Distribution | Command |
---|---|
Debian | apt-get install execline |
Ubuntu | apt-get install execline |
Alpine | apk add execline |
Kali Linux | apt-get install execline |
Fedora | dnf install R-core |
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