Friday, November 15, 2024
Google search engine
HomeGuest BlogsLinux exec Command With Examples

Linux exec Command With Examples

Introduction

The Linux exec command executes a Shell command without creating a new process. Instead, it replaces the currently open Shell operation. Depending on the command usage, exec has different behaviors and use cases.

This article demonstrates how to use the exec command in Linux.

Linux exec Command With ExamplesLinux exec Command With Examples

Prerequisites

Linux exec Command Syntax

The exec command syntax is:

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

The command behaves differently depending on the number of arguments:

  • If an argument is present, the exec command replaces the current shell with the executed program. In a Bash script, any commands after do not get executed.
  • If no command argument is present, all redirections occur in the current shell.

The exec command never returns to the original process unless there’s an error or the command runs in a subshell.

Linux exec Command Options

Below is a brief explanation of all exec options:

Option Description
-c Executes the command in an empty environment.
-l Passes a dash (-) as the zeroth argument.
-a [name] Passes a [name] as the zeroth argument.

Continue reading to see how exec works through examples.

Linux exec Command Examples

The examples below demonstrate the behavior of the exec command in the terminal and through Bash scripts.

Basic Use (Process Replacement)

To see how exec works, do the following:

1. Open the terminal and list the running processes:

ps
ps bash pid terminal outputps bash pid terminal output

The output shows the currently running Bash shell and the ps command. The Bash shell has a unique PID.

2. To confirm, check the current process ID with:

echo $$
echo pid current processecho pid current process

The PID is the same as the output from the ps command, indicating this is the currently running Bash process.

3. Now, run exec and pass the sleep command for one hundred seconds:

exec sleep 100

The sleep command waits for 100 seconds.

4. In another terminal tab, list all currently running processes and grep the sleep command:

ps -ae | grep sleep
ps -ae grep sleep terminal outputps -ae grep sleep terminal output

The PID for the process is the same as the Bash shell PID, indicating the exec command replaced the Bash shell process.

The Bash session (terminal tab) closes when the one hundred seconds are complete and the process ends.

Replace Current Shell Session

Use the exec command to replace the current shell session:

1. Check the current shell PID:

echo $$

2. Use exec to switch to the Bourne Shell:

exec sh
exec sh current pid terminal outputexec sh current pid terminal output

3. In another tab, check the PID for the Bourne Shell process:

ps -ae | grep "\bsh\b"
ps -ae grep sh terminal outputps -ae grep sh terminal output

Note: The \b in grep is Regex for matching word boundary, allowing an exact match of sh in the output. Learn more in our Grep Regex tutorial.

The command replaces the Bash process. Exiting the Bourne Shell exits the terminal session completely.

Program Calls With exec in Bash Scripts

To see how exec works in Bash scripts, do the following:

1. Open a text editor, such as Nano, and create a script file:

nano [script name]

2. Paste the following code:

#!/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
exec in bash script selectionexec in bash script selection

The script does the following:

  • Line 3 creates an infinite while loop.
  • Lines 5-7 print the three possible options.
  • Line 8 reads the user’s input into the variable $Input.
  • Line 9 starts a case statement checking the user’s input.
  • Lines 10-11 execute the apt update or apt upgrade command in place of the current shell. When the update or upgrade process ends, the terminal session exits.
  • Line 12 uses the break statement to exit the infinite while loop and ends the script. The session returns to the current shell as usual.

3. Save the script and close Nano.

4. Run the Bash script in the current environment to see the results:

. [script name]
exec script running terminal outputexec script running terminal output

Executing the script with the source command applies the script behavior to the current Bash shell. Use exec to run Bash scripts within other programs for a clean exit.

Logging Bash Scripts

The exec command finds use in manipulating file descriptors for error logging in Bash scripts. The default Linux file descriptors are:

  • stdin (0) – Standard in
  • stdout (1) – Standard out
  • stderr (2) – Standard error

Use the exec command and redirect the file descriptors to a file to create logs. To see how logging works, follow the steps below:

1. Create a sample Bash script:

nano logging.sh

2. Paste the code into the file:

#!/bin/bash

# Create test.log file
touch test.log

# Save test.log to log_file variable
log_file="test.log"

# Redirect stdin to $log_file
exec 1>>$log_file

# Redirect stderr to the same place as stdin
exec 2>&1

echo "This line is added to the log file"
echo "And any other lines after"
eho "This line has an error and is logged as stderr"
logging.sh script contentslogging.sh script contents

The script redirects all command outputs and errors to the same file (test.log).

3. Save the script and close the text editor.

4. Change the script permission to executable:

chmod +x logging.sh

5. Run the script:

./logging.sh

The script does not output any code. Instead, all the output logs to the test.log file.

6. Use the cat command to see the test.log file contents:

cat test.log
exec stdin and stderr logging terminal outputexec stdin and stderr logging terminal output

The log file contains all the standard outputs and error messages. Use exec to debug scripts and log inputs, outputs, or errors depending on the situation.

Run Scripts in a Clean Environment

The -c option for the exec command creates a clean environment. To demonstrate, do the following in the terminal:

1. Start a new Bash shell session:

bash

2. Use the printenv command to print all the environment variables in the current Bash shell:

printenv
printenv bash shell terminal outputprintenv bash shell terminal output

The command prints all the environment variables for the current Bash shell session.

3. Run the same command using exec with the -c flag:

exec -c printenv
exec -c printenv clean environment termianl outputexec -c printenv clean environment termianl output

The command printenv runs in a clean environment, and no variables output to the console. Use the -c option to run scripts or commands in clean environments.

exec With find Command

The find command in Linux has the exec command as an option to execute an action on discovered content. For example, the line below executes the chmod command on the find command results:

sudo find ~ -name "test.log" -exec chmod +x '{}' \;
find and exec command terminal outputfind and exec command terminal output

The find command searches through the home directory (~) for the test.log file and executes the permission change.

Conclusion

After following the examples from this tutorial, you should know how to use the exec command effectively in Bash scripts.

Next, learn how to execute a job automatically on reboot using Crontab.

Was this article helpful?
YesNo

RELATED ARTICLES

Most Popular

Recent Comments