What is Exec Command in Linux?

Topics Covered

Overview

Without explicitly stating the redirection operator and log file name after each echo statement, we may want to redirect the output of all the echo statements into a log file while writing Bash scripts. A potent built-in tool that may be used for this is the bash exec command.

In this lesson, we'll look at how to add output and error logging to shell scripts using the linux exec command. We'll also look at several more use for this command in shell scripts.

What is Exec Command in Linux:

The Linux exec runs a shell instruction without launching a new task. In place of doing this, It replaces the currently running shell operation. Based on how the command is used, linux exec offers a range of characteristics and use cases.

Prerequisites

  • Access to the linux terminal.
  • Understanding of the fundamental Linux terminal controls.
  • A linux text editor like nano.

Linux provides a wide range of commands that enable users to complete various activities quickly. Among them, the linux exec command stands out as a potent tool that makes it easier to execute processes, swap out scripts, and even initialize shells. This article will examine the possibilities and capabilities of the exec command in Linux, illuminating its application and providing real-world examples.

Syntax

The majority of Linux shells, including Bash, provide the built-in command exec. It essentially starts a new process by switching out the old process image for a new one. Linux exec substitutes a new program, script, or command for the active shell process, in contrast to other commands that create subprocesses.

Depending on how many arguments are provided, the command behaves differently:

  • If an optional argument is given, the linux exec will replace the currently running shell with the executed program. Any instructions that come after are not executed in a Bash script.
  • The current shell is used for all redirections if there is no command argument.

Unless there is an issue or whether it is running in a subshell, the linux exec never returns to the originating process.

Linux Exec Command Options:

FlagExplanation
-cThe command is run in a blank environment.
-lA dash (-) is accepted in the form of 0th parameter.
-a [name][name] is passed in the form of 0th argument.

To understand how exec functions with illustrations, keep reading.

Examples of Linux Exec Commands

The exec command offers several powerful features that can significantly enhance productivity and efficiency in Linux environments. Let's delve into some of its notable capabilities.

Basic Utilisation (Process Replacement)

Exec's main purpose is to switch out the existing process for a new one. By using this capability, a program or script can be run directly without the need for a subprocess. The requirement for an additional layer of subprocesses is eliminated when the new process uses the exec command to take over the resources of the existing process.

Try the following to see how Linux exec functions:

1. Launch the terminal and identify the active processes

Launch the terminal and identify

The ps command and the currently active Bash shell are displayed in the output. The PID for the Bash shell is special.

2. Verify the present process ID by using

Verify the present process ID by using

The PID confirms that the currently running bash process is identified by matching the output of the ps command.

3. Next, run exec for 90 seconds while giving the sleep command

The command sleep will wait for 90 seconds.

4. List all processes that are open in another terminal tab, then grep for the sleep command

another terminal tab

The exec instruction superseded the bash shell process, as evidenced by the fact that the PID of the process matches that of the Bash shell. When the hundred seconds are up and the procedure is finished, the Bash session (terminal tab) stops.

Replace the Current Shell Session to new

Iwithbash scripts, you can use the exec command to replace the current process with a new program. This means that the current script will be replaced entirely by the specified program, and the script will not continue executing after the exec command.

Using the exec command, you can switch out the currently running shell session:

1. Verify shell's PID right now

2. Use exec: to change to the Bourne Shell

Bourne Shell

3. Verify the PID for the Bourne Shell process in a different tab.

Bourne Shell process

It's important to note that replacing the current shell session with a new one can be useful in certain scenarios, such as when you want to switch to a different shell or reset the shell environment.

However, be cautious when using the exec command to avoid accidentally losing unsaved work or terminating important processes running in the original shell session.

Note

She can be exactly matched in the output since the b in grep is a Regex which is meant for matching the word boundaries.

A string of text known as a "regex" allows you to build patterns that help with text management, matching, and location. Perl is a programming language that uses regular expressions. This is merely one of the many places where regular expressions can be found. Regular expressions can also be used in text editors and from the command line to find text within a file.

The bash process is replaced by the command. The terminal session ends when you leave the Bourne Shell.

Programme Calls in Bash Scripts Using exec

Try the following to see how Linux exec functions in Bash scripts:

1. Create a script file by opening a text editor like Nano

2. Use the given code

script accomplishes

This is what the script accomplishes:

  • 3rd line: establishes an endless while loop.
  • 5th-7th line: Print out the 3 alternatives.
  • 8th line: The variable $Input is filled with the user's input.
  • 9th line: A special statement that checks the user-given input is introduced.
  • 10th-11th line: The apt upgrade command replaces the current shell. The terminal session stops after the update or upgrade process is finished.
  • 12th line: The script is terminated by using the break code to get out of the endless while loop. The session resumes in the default shell.

3. Save the script, then shut Nano off.

4. To see the outcomes, execute the Bash script in the present environment

Bash script

The behavior of the script is implemented in the current bash shell when the source command is used to run it. Run bash scripts inside of other programs using exec for an exit.

Bash Logging Scripts

Linux exec command is useful for modifying file descriptors in Bash scripts that log errors. Linux's standard file terms are:

  • stdin (0) means Standard input
  • stdout (1) means Standard output
  • stderr (2) means Standard error

You can utilize the exec command to generate logs and point to the file descriptors. The procedures listed below will show you how logging functions:

1. Make an example Bash script first

2. Add the code in the document

saving the script

The script sends test.log, a single file, as the destination for all command outputs and errors.

3. After saving the script, close your editor.

4. Make executable the script rule

5. Execute the script

There is no code output by the script. Instead, the test.log file receives all the output logs.

6. Use the cat command.log file information to view the test.

cat command log

All of the usual outputs and error messages are contained in the log file. Depending on the circumstance, use exec to debug scripts.

Run Scripts in a Splendid Setting

The exec command provides a clean environment when the -c option is used. Try the following in the terminal to show what I mean:

1. Open a fresh Bash shell window

2. To view all available environment variables, use the printenv command

Run Scripts in a Splendid

3. Execute the following command using the exec parameter -c

variables that write to the terminal

There are no variables that write to the terminal while the command printenv is running in a clean environment. To execute commands or scripts in sterile conditions, use the -c option.

Exec with find Command

The exec command in Linux, when combined with the find command, becomes a powerful tool for performing actions on files or directories that match specific criteria. By using exec with find, you can execute commands or scripts on the files found by the find command. Here are some examples to illustrate the usage of exec with find:

1. Delete all files with a specific extension

This command finds all files with the .txt extension in the specified directory and its subdirectories, then executes the rm command to delete each file found.

2. Change the ownership of files matching a certain pattern

In this example, find locates all files in the specified directory that start with file and have the .txt extension. The exec command then executes chown to change the ownership of each file to newowner.

3. Execute a script on all directories matching a specific name

This command searches for directories named "targetdir" in the specified directory and its subdirectories. For each matching directory found, the exec command executes the script located at "/path/to/script.sh", passing the directory path as an argument to the script.

4. Compress all files older than a certain date

In this example, find identifies all files in the specified directory that are older than 7 days (-mtime +7). The exec command then executes the gzip command to compress each of these files.

By combining exec with find, you can perform a wide range of actions on files or directories that match specific conditions. It provides a flexible and efficient way to automate tasks and process large sets of files in Linux.

Conclusion:

In conclusion, let's summarize the key points about the exec command in Linux:

  • In Linux, the exec command replaces the current process with a new program or script.
  • It is a built-in command available in most Linux shells, including Bash.
  • Exec facilitates efficient process execution by eliminating subprocess overhead.
  • It can be used for shell initialization, ensuring that a specific program or script becomes the main process running in the shell environment.
  • By utilizing exec within a script, performance can be improved by avoiding the overhead of creating additional subprocesses.
  • Exec allows for file descriptor manipulation, enabling control over input/output redirection within a process.
  • Understanding and effectively using the exec command enhances productivity and efficiency in Linux environments.

The exec command in Linux empowers users to efficiently execute programs, scripts, and commands while managing system resources effectively. Its ability to replace the current process, initialize the shell, and manipulate file descriptors makes it a valuable tool for optimizing workflows and streamlining tasks.