6 Examples of the Linux exec Command For Process Management

Try this guide with our instant dedicated server for as low as 40 Euros

Linux exec Command

The Linux exec command is a powerful tool for process management in Unix-like operating systems. This command allows the replacement of the current process image with a new one without creating a new subprocess. 

This feature is particularly useful for script execution, process substitution, and managing shell execution environments. By leveraging Linux exec, users can efficiently manage file descriptors and execute commands with altered behavior directly within the current process. 

In this comprehensive tutorial, we will start with an overview of the exec command. Next, we will look into the practical applications of Linux exec, demonstrating its utility in optimizing performance and streamlining process control in Linux system administration and shell scripting.

Table Of Contents

  1. An Overview of the Linux exec Command
  2. The Linux exec Command Options
  3. 6 Examples Of the Linux exec Command
    1. The Prerequisites
    2. Example #1: Process Replacement
    3. Example #2: Replacement of Current Shell Session
    4. Example #3: Program Calls With exec in Bash Scripts
    5. Example #4: Use the Linux exec Command for Bash Script Logging
    6. Example #5: Run Scripts in a Clean Environment
    7. Example #6: Integrating exec with the find Command
  4. Conclusion
  5. FAQs

An Overview of the Linux exec Command

The command syntax for the Linux exec command is as follows:

# exec [options] [command [arguments]] [redirection]

The functionality of the exec command changes depending on the number of arguments supplied by the user

If a command argument is specified, the Linux exec command replaces the current process with the command argument. Consequently, in a Bash script, any commands following it do not execute with output logs.

In the absence of a command argument, all redirections take place within the current shell.

Linux exec does not revert to the original process unless it encounters an error or is running within a subshell.

The Linux exec Command Options

Here are the most commonly used options for the Linux exec command:

linux exec command options

6 Examples Of the Linux exec Command 

Now that you have a clear understanding of how the Linux exec command works, let’s discuss some use cases where we will show you how to use the command to achieve specific outcomes. 

The Prerequisites

Before trying out the examples we will discuss later on, you should make sure you have the following:

  • A system running a popular Linux distribution.
  • A user account with root or sudo privileges.

Example #1: Process Replacement

Let’s start with a basic example of using the exec command. 

Launch the terminal and list the active processes:

# ps

ps

As you can see, the output of the command on our test system shows the running Bash shell and the ps command, each associated with a unique PID in the current shell environment.

Next, get the current process ID by the following echo command:

# echo $$

echo $$

This ID should match the PID of the running Bash command obtained in the output of the previous ps command.

Execute Linux exec and provide the sleep command to delay execution for one hundred seconds:

# exec sleep 100

exec sleep 100

The sleep command will pause for the specified duration.

Launch a new terminal, list all running processes, and filter for the sleep command:

# ps -ae | grep sleep

 The PID for the sleep command should correspond to the PID of the Bash shell, confirming that the exec command replaced the original Bash process.

The Bash session will terminate upon completing the one-hundred-second sleep duration, concluding the process.

Example #2: Replacement of Current Shell Session

You can replace the current shell session using the Linux exec command. 

Start by getting the PID of the current shell:

# echo $$

Next, use the exec command to transition to the Bourne Shell:

# exec sh

exec sh

Launch another terminal to get the PID for the Bourne Shell process by running the following command:

# ps -ae | grep "\bsh\b"

ps -ae

You can see that the exec replaces the current shell session with the Bourne Shell.

Example #3: Program Calls With exec in Bash Scripts

Let’s use the Linux exec in a Bash script to see how you can tap into the power of this versatile command.

Use your favorite text editor to create a new Bash script file. We will use Vi for the demonstration.

 # vi [script name]

Add the following lines to the file:

# !/bin/bash

while true

do

    echo "1. Update "

    echo "2. Upgrade "

    echo "3. Exit"

    read Input

    case "$Input" in

        1) exec sudo apt update;;

        2) exec sudo apt upgrade;;

        3) break;;

    esac

done

bin bash

Here is a breakdown of this script: 

Line 3:            An infinite while loop.

Lines 5-7:      Displays the three options.

Line 8:            Get the user input in the Input variable.

Line 9:            Start the case statement structure to assess the user’s input.

Lines 10-11: The Linux exec command executes apt update or apt upgrade by replacing the existing shell. Note that after finishing the update or upgrade operation, the terminal session ends.

Line 12:          The break statement is used to exit the infinite loop and terminate the script, reverting the session to the current shell.

Execute the Bash script within the current environment to observe the outcomes:

# . [script name]

Executing the script using the source command integrates its functionality into the existing Bash shell.

Also Read: Bash eval Statement in Linux Shell Scripts With 7 Examples

Example #4: Use the Linux exec Command for Bash Script Logging

In Bash scripting, the exec command manipulates file descriptors, particularly for error logging. 

Most Linux distros use the following standard file descriptors:

standard file descriptors

You can use the exec command to redirect these file descriptors to a designated file for logging purposes. 

Begin by creating a sample Bash script:

# vi logging. sh

Insert the following code into the file:

#!/bin/bash

#Create test.log file

touch test.log

#Assign test.log to the log_file variable

log_file="test.log"

#Redirect stdout to $log_file

exec 1>>"$log_file"

#Redirect stderr to the same location as stdout, i.e., redirection error

exec 2>&1

echo "This line is appended to the log file"

echo "And any subsequent lines."

echo "This line encounters an error and is logged as stderr."

bin bash touch test log

Save and exit the text editor. Next, run the following command to mark the script as executable:

# chmod +x logging.sh

Finally, execute the script:

# ./logging.sh

The script does not display any output in the terminal. Instead, all output is logged to the test.log file.

We recommend using the cat command to view the contents of test.log:

# cat test.log

cat test.log

Example #5: Run Scripts in a Clean Environment

Executing commands in a “clean” environment is an important application of the exec command. 

The -c flag facilitates the execution of commands within a clean environment.

Initiate a new Bash shell session by typing the following command: 

# bash

Next, list all environmental variables present in this Bash shell session by executing:

# printenv

printenv

Now combine the printenv command with the exec -c to repeat the process: 

# exec -c printenv

In this scenario, printenv operates within a clean environment without environmental variables being shown in the console output. The -c flag is instrumental in ensuring scripts or commands run without any interference from the local environmental variables.

Example #6: Integrating exec with the find Command

You can combine find with the exec command to perform actions on found items. For instance, you can run the following command to execute the chmod command on files identified by the find command to make them executable:

# sudo find ~ -name "test.log" -exec chmod +x '{}' \;

sudo find

When this command is executed, the find command searches the user’s home directory (~) for all file names containing test.log and modifies their permissions accordingly. This demonstrates the seamless integration between find and exec commands in modifying file permissions based on search results.

Also Read: lsof Command in Linux with Examples

Conclusion

The Linux exec command is a powerful tool for managing command execution within the Linux operating system. Its capability to replace the current shell process with a new command process, especially with the -c flag, allows operations in a clean environment devoid of previous environmental variables. 

This feature ensures that scripts or commands run in an isolated setting, reducing the risk of interference from pre-existing settings or variables. Furthermore, the exec command’s integration with other Linux commands, like find, expands its utility, enabling users to perform complex tasks such as searching for files and applying changes to them in one go.

At RedSwitches, we take pleasure in assisting our valued customers with their unique server needs. Our range of customizable bare metal servers is designed to provide reliable infrastructure for your projects. We understand the importance of competitive pricing, so we offer instant dedicated server options at affordable rates. When you choose us, you can expect a seamless experience as we prioritize swift delivery, typically fulfilling orders approved on the same day. Whether you require a dedicated server, a traffic-friendly 10Gbps dedicated server, or a high-performance bare metal server, we are here to be your trusted hosting partner.

FAQs

Q. What is the exec command in Linux?

The exec command in Linux executes a command that replaces the current shell process. It doesn’t spawn a new process; instead, it executes the command within the existing process, saving system resources and making script execution more efficient.

Q. How does the exec command affect environmental variables?

Normally, exec inherits the environmental variables from the current shell. However, when used with the -c option, exec initiates a command in a clean environment, meaning it starts with no environmental variables, ensuring the command runs in a more controlled and predictable environment.

Q. Can you use the exec command with scripts?

Yes, you can use the exec command to execute scripts. When a script is executed with exec, the script runs within the current shell process, and upon completion, the shell exits. This is particularly useful for scripts that need to alter the environment of the current shell.

Q. How can the exec command be utilized with the find command?

You can employ the exec command alongside the find command by using the -exec option. This enables the execution of a designated command on every file that the find command locates. For example, changing file permissions or moving them. It’s a powerful combination for batch-processing files based on search criteria.

Q. What happens to the shell after executing a command with exec?

After executing a command with exec, the current shell process ends, and control is transferred to the executed command. If the exec command is used in a script, the script and the shell executing it terminate once the exec command’s process finishes.

Q. Can you revert to the original shell after executing an exec command?

No, once the exec command is executed, the original shell process is replaced, and it cannot be reverted to. Any commands following the exec in a script or shell will not be executed, as the exec command’s process will have replaced the shell process.

Q. Can you return to the initial shell after running an exec command?

While exec is efficient, it’s important to use it cautiously, especially in scripts. Since it replaces the current shell, any commands that follow it in a script will not be executed if the exec is successful. Additionally, when running commands in a clean environment using -c, ensure that the command does not rely on environmental variables that might be missing.

Q. How can I troubleshoot issues with commands executed using exec?

Debugging commands run with exec can be done by checking the command’s syntax and ensuring all needed environmental variables are passed correctly, especially when using the -c option. Logging command outputs before using exec might also help troubleshoot issues.

Try this guide with our instant dedicated server for as low as 40 Euros