Linux execute command in shell

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.

Читайте также:  Linux изменить яркость экрана

And here’s the output if you execute the shown script:

use the exec command in the shell script to replace the process

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:

use exec command in shell script to store logs

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:

use exec command in shell script to change the standard input to read the file

4. Change file descriptors using exec in the shell script (advanced)

There are three standard file descriptors in Linux:

  1. Standard input (stdin - file descriptor 0)
  2. Standard output (stdout - file descriptor 1)
  3. 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.

Читайте также:  Linux cannot find shared library

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:

Change file descriptors using exec in the shell 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 Commands from Within a Shell Script

“Working with shell script is something any Linux user should be at home with. However, how you learn to execute commands plays a big role in your understanding and working with shell scripts. This guide explains all details about executing commands within a shell script. We will cover everything from creating a shell script to defining variables to executing the shell script. Let’s get started!”

Executing Commands From a Shell Script

The shell is an interpreter that allows users to work and interact with the Linux system. The shell works as a command-line interpreter, taking inputs and giving output. A shell script can contain loops, functions, variables, and commands. The best thing with shell scripts is how they make automating tasks easy. Let’s get into the details of executing commands in a shell script.

Creating a Shell Script

A shell script has the .sh extension, and you can create a shell script using an editor, provided you save the file using the .sh extension. In this case, we will create a linuxhint.sh script using the nano editor.

Once the file opens, the line below is the first thing you must write for the system to know that you are working with a shell script.

With your shell script constructed, we can proceed to see how to execute commands inside the script.

Executing Commands Within a Shell Script

A shell script supports the built-in Linux commands. It works similarly to how you would execute Linux commands on your terminal. For instance, if you want to execute commands to get the current date and time and display the logged-in user, you could use the date and who commands by typing them as shown.

Читайте также:  Microsoft sql server linux odbc driver

Executing a Shell Script

Once you’ve defined the commands you want to execute, save the bash script. Before you execute the script, we must first make it executable using the syntax below.

Once it is executable, you can execute the script using the syntax below.

Working With Variables

Shell scripts allow the creation of user-defined variables to hold the output of given commands. To hold the command’s output inside a variable, enclose the command using $(). For instance, if we needed to get the current date using the date command and store it in a variable, we could define our variable as shown below.

Note that there shouldn’t be any spacing between the words in the line.

If you want to create user-defined variables, write the variable name, and the value should be enclosed in double quotes. For instance, check the variable below.

Once the variable is created, you can call it using the $ followed by the variable name. You can then execute the command using the echo command.

The output would execute as expected based on the commands we added.

Working With Interactive Shell Commands

With a shell script, you can work with commands and variables that interact with the user through inputs to determine the output. As shown below, we use the read command to get the user input and echo the output.

Defining Functions

You can also execute commands through functions in the shell script. A function can take any number of arguments, and you can create a function to execute any command. Below is a shell script with a function that creates a folder and five files inside it.

Here’s the output after executing the script.

Conclusion

Shell scripts are not that challenging to work and create. With a few tricks, you can easily use different commands in your shell scripts to achieve much functionality. In this guide, we’ve seen the various ways you can execute commands within a shell script. Hopefully, you now have a foundation for creating shell script commands.

About the author

Denis Kariuki

Denis is a Computer Scientist with a passion for Networking and Cyber Security. I love the terminal, and using Linux is a hobby. I am passionate about sharing tips and ideas about Linux and computing.

Источник

Оцените статью
Adblock
detector