Open In App

exec command in Linux with examples

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The ‘exec’ command in Linux is a powerful shell built-in used to replace the current shell process with a new command process. Unlike typical commands that create a new process, ‘exec’ transforms the existing process, directly impacting the efficiency and behavior of scripts.

What is the exec Command?

‘exec’ overrides the current shell session with a specified command without creating a new process. This unique property makes ‘exec’ particularly useful for modifying the shell environment or executing commands with performance in mind, as it avoids the overhead of spawning a new process.

Syntax:

exec [-cl] [-a name] [command [arguments]] [redirection ...]

Options:

  • ‘-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.

Key Behaviors of ‘exec’ Command

The exec command can be used in two modes:

1. 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.

Example 1:Example 2:The ‘exec’ command searches the path mentioned in the ‘$PATHvariable 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.

2. 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.

Example: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.

Conclusion

The ‘exec’ command is a versatile tool in the Linux shell scripting arsenal. It allows for efficient process management by replacing the current shell with a command instead of creating a new one. By utilizing the various options and behaviors of ‘exec’, users can significantly enhance the functionality and performance of their scripts.


Next Article
Article Tags :

Similar Reads