You can assign the output of a shell command to a variable in a bash shell script by using the following syntax:
VARIABLE_NAME=$(command)
For example, to assign the output of the ls command to a variable called FILES, you would use the following syntax:
FILES=$(ls)
One of the fundamental features of a shell script is the ability to run shell commands and capture their output for further processing. In this tutorial, you will learn how to assign the output of a shell command to a variable in a bash shell script.
How to Assign Output of Shell Command To Variable in Bash Shell Script
By following the steps outlined in this tutorial guide, you can easily capture the output of any shell command and use it in further processing.
- Step 1: Run the Command
- Step 2: Assign the Output to a Variable
- Step 3: Display the Variable
- Step 4: Use the Variable in Further Processing
Step 1: Run the Command
The first step is to run the shell command whose output you want to capture. For example, let’s say we want to capture the output of the ls
command. In the bash shell, you can run the command by typing:
ls
This will list all the files and directories in the current working directory.
Step 2: Assign the Output to a Variable
To assign the output of the command to a variable, you can use the following syntax:
variable=$(command)
Here, variable
is the name of the variable that you want to assign the output to, and command
is the shell command whose output you want to capture. For example, to assign the output of the ls
command to a variable named files
, you can use the following command:
files=$(ls)
Step 3: Display the Variable
You can display the variable by using the echo
command. For example, to display the contents of the files
variable, you can use the following command:
echo $files
This will display the output of the ls
command that was assigned to the files
variable.
Step 4: Use the Variable in Further Processing
Once you have captured the output of the command in a variable, you can use it in further processing. For example, you can use the output of the ls
command to check if a file exists in the directory or to perform some other operation.
Conclusion
In conclusion, assigning the output of a shell command to a variable in a bash shell script is a simple and powerful feature that can help you automate your tasks and perform complex operations. By following the steps outlined in this tutorial, you can easily capture the output of any shell command and use it in further processing.