- Using exec Command in Bash Shell Scripts
- 1. Use the exec command to replace process in shell script
- 2. Use exec command in shell scripts for logging
- 3. Change standard input to read files using exec
- 4. Change file descriptors using exec in the shell script (advanced)
- Do more by pairing exec with the find command
- How To Execute a Command with a Shell Script in Linux
- Prerequisites
- Getting Started
- Creating and Running a Basic Shell Script
- Using Variables in Shell Scripts
- Reading Input from the Command Line
- Defining Functions
- Conclusion
Using exec Command in Bash Shell Scripts
The exec command in shell scripts is super useful for logging, reading from files and running commands by replacing the current process.
The shell built-in exec command is used for executing commands in shell scripts.
Wait! Don’t shell scripts execute Linux commands already? They do. But exec runs the Linux commands without starting a new process. It replaces the shell process with the specified command.
Seems complex? Let me give you some examples of using the exec command in shell scripts:
- Process replacement
- Logging within the shell script
- Change standard input to read a file
- Change file descriptors
So let’s start with the first one.
1. Use the exec command to replace process in shell script
Replacing the process is one of the most known implementations of exec in the shell script.
So here, I will be using a simple script that will display how the exec command in the script can be used to replace the current shell process.
First, use the following command to use the nano to create and edit a new script:
nano process_replacement.sh
#!/bin/bash echo "Before exec: This is the original script" exec ls -l echo "After exec: This line will not be executed"
Now, let me explain what this script will do.
Here are three command statements. First will print the basic text indicating the original script which is meant to be replaced.
The second statement involves the usage of the exec command with the ls command to list the contents of the current working directory and it will replace the previous process too!
Now, the third statement won’t be executed as the process was replaced by the exec previously, and there were no additional arguments to support the execution of the third command statement.
Simply put, the process will be replaced by the 2nd command argument, and the 3rd command won’t be executed.
And here’s the output if you execute the shown script:
And as you can see, the 3rd command statement which was supposed to print «After exec: This line will not be executed» is shown here.
That does not seem very practical? Here’s another example.
2. Use exec command in shell scripts for logging
Yet another interesting and easy implementation of the exec is where you can redirect the output to a file.
Here, I will be using 3 arguments, two for the standard output and one for standard error.
#!/bin/bash LOG_FILE="script.log" # Redirect stdout and stderr to the log file exec &> "$LOG_FILE" # Start logging echo "Script started at $(date)" # Perform some operations echo "Performing operation 1 (stdout). " ls -l /path/to/directory echo "Performing operation 2 (stderr). " grep "search term" /path/to/nonexistentfile echo "Performing operation 3 (stdout). " cat /path/to/file # Log completion echo "Script completed at $(date)"
I have created an empty file named script.log in the same directory where the above script is located to store the logs.
Here, the exec command will redirect the output to the log file including when is started and ended.
When I ran the script, the file containing the log file looked like this:
3. Change standard input to read files using exec
This can be very helpful when performing certain operations over the file.
Here, I will be using a simple text file named Hello.txt that contains some random text lines:
Ubuntu, openSUSE, Arch, Debian, Fedora + - / * 2 4 6 1 4 6 1 2
And here’s the script which will read from the file and output the contents to the standard output:
#!/bin/bash INPUT_FILE="Hello.txt" # Redirect stdin to read from a file exec < "$INPUT_FILE" # Read the entire file as a single input content=$(cat) # Process the input echo "Read: $content"
Now, let me explain the script.
And if you execute the script, the result will look like this:
4. Change file descriptors using exec in the shell script (advanced)
There are three standard file descriptors in Linux:
- Standard input (stdin - file descriptor 0)
- Standard output (stdout - file descriptor 1)
- Standard error (stderr - file descriptor 2)
And using the exec command, you can change the descriptors. For example, you can use any number to use the preferred data stream, such as using 3 for stdin.
Let me share the script first and then explain how it functions:
#!/bin/bash # Open a file for writing exec 3> output.txt # Redirect stdout to file descriptor 3 exec 1>&3 # Print some output echo "This is a test message" # Close the file descriptor exec 3>&-
Here, I have opened a output.txt file and assigned file descriptor 3 which means anything sent to file descriptor 3 will be written to the file.
Using exec 1>&3 , I have redirected the standard output (1) to the file descriptor 3 which means anything written to the standard output will be sent to the file descriptor 3 (to the output.txt in my case).
The echo statement prints the text to the standard output (which will be sent to the file as we changed the file descriptor earlier).
And exec 3>&- kills the file descriptor 3 as it is no longer needed!
You can expect the following results after executing the above script:
Do more by pairing exec with the find command
Did you know that you can use the find command with the exec and trust me, it makes a killer combination?
And if you want to learn how to, here's a detailed guide:
I hope you will find this guide helpful. And if you have doubts, leave a comment.
How To Execute a Command with a Shell Script in Linux
Shell is a command-line interpreter that allows the user to interact with the system. It is responsible for taking inputs from the user and displaying the output.
Shell scripts are a series of commands written in order of execution. These scripts can contain functions, loops, commands, and variables. Scripts are useful for simplifying a complex series of commands and repetitive tasks.
In this article, you will learn how to create and execute shell scripts for the command line in Linux.
Prerequisites
To complete this tutorial, you will need:
- Familiarity with using the terminal.
- Familiarity with a text editor.
- Familiarity with commands like chmod , mkdir , and cd .
Getting Started
A shell script needs to be saved with the extension .sh .
The file needs to begin with the shebang line ( #! ) to let the Linux system know which interpreter to use for the shell script.
For environments that support bash , use:
For environments that support shell , use:
This tutorial assumes that your environment supports bash .
Shell scripts can also have comments to increase readability. A good script always contains comments that help a reader understand exactly what the script is doing and the reasoning behind a design choice.
Creating and Running a Basic Shell Script
You can create a shell script using the vi editor, a cat command, or a text editor.
For this tutorial, you will learn about creating a shell script with vi :
This starts the vi editor and creates a basic_script.sh file.
Then, press i on the keyboard to start INSERT MODE . Add the following lines:
This script runs the commands whoami and date . whoami displays the active username. date displays the current system timestamp.
To save and exit the vi editor:
Finally, you can run the script with the following command:
You may get output that resembles the following:
Outputroot Fri Jun 19 16:59:48 UTC 2020
The first line of output corresponds to the whoami command. The second line of output corresponds to the date command.
You can also run a script without specifying bash :
Running the file this way might require the user to give permission first. Running it with bash doesn’t require this permission.
Output~bash: ./basic_script.sh: Permission denied
The command bash filename only requires the read permission from the file.
Whereas the command ./ filename , runs the file as an executable and requires the execute permission.
To execute the script, you will need to update the permissions.
This command applies chmod and gives x (executable) permissions to the current user.
Using Variables in Shell Scripts
Scripts can include user-defined variables. In fact, as scripts get larger in size, it is essential to have variables that are clearly defined and that have self-descriptive names.
Add the following lines to the script:
#!/bin/bash # This is a comment # defining a variable GREETINGS="Hello! How are you" echo $GREETINGS
GREETINGS is the variable defined and later accessed using $ (dollar sign symbol. There should be no space in the line where variables are being assigned a value.
This prints out the value assigned to the variable:
When the script is run, GREETINGS is defined and accessed.
Reading Input from the Command Line
Shell scripts can be made interactive with the ability to accept input from the command line. You can use the read command to store the command line input in a variable.
Add the following lines to the script:
#!/bin/bash # This is a comment # defining a variable echo "What is your name?" # reading input read NAME # defining a variable GREETINGS="Hello! How are you" echo $NAME $GREETINGS
A variable NAME has been used to accept input from the command line. This script waits for the user to provide input for NAME . Then it prints NAME and GREETINGS .
OutputWhat is your name? Sammy Sammy Hello! How are you
In this example, the user has provided the prompt with the name: Sammy .
Defining Functions
Users can define their own functions in a script. These functions can take multiple arguments.
Add the following lines to the script:
#!/bin/bash #This is a comment # defining a variable echo "What is the name of the directory you want to create?" # reading input read NAME echo "Creating $NAME . " mkcd () mkdir "$NAME" cd "$NAME" > mkcd echo "You are now in $NAME"
This script asks the user for a directory name. Then, it uses mkdir to create the directory and cd into it.
OutputWhat is the name of the directory you want to create? test_dir Creating test_dir . You are now in test_dir
In this example, the user has provided the prompt with the input: test_dir . Next, the script creates a new directory with that name. Finally, the script changes the user’s current working directory to test_dir .
Conclusion
In this article, you learned how to create and execute shell scripts for the command line in Linux.
Consider some repetitive or time-consuming tasks that you frequently perform that could benefit from a script.
Continue your learning with if-else , arrays, and arguments in the command line.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.