exec command in Linux is used to execute a command from the bash itself. This command does not create a new process it just replaces the bash with the command to be executed. If the exec command is successful, it does not return to the calling process.
exec [-cl] [-a name] [command [arguments]] [redirection ...]
- c: It is used to execute the command with empty environment.
- a name: Used to pass a name as the zeroth argument of the command.
- l: Used to pass dash as the zeroth argument of the command.
Note: exec command does not create a new process. When we run the exec command from the terminal, the ongoing terminal process is replaced by the command that is provided as the argument for the exec command.
The exec command can be used in two modes:
- Exec with a command as an argument: In the first mode, the exec tries to execute it as a command passing the remaining arguments, if any, to that command and managing the redirections, if any.
The exec command searches the path mentioned in the $PATH variable to find a command to be executed. If the command is not found the exec command as well as the shell exits in an error.
- Exec without a command: If no command is supplied, the redirections can be used to modify the current shell environment. This is useful as it allows us to change the file descriptors of the shell as per our desire. The process continues even after the exec command unlike the previous case but now the standard input, output, and error are modified according to the redirections.
Here the exec command changes the standard out of the shell to the tmp file and so all the commands executed after the exec command write their results in that file. This is one of the most common ways of using exec without any commands.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.