Command Substitution
Command substitution allows us to take the output of a command or program and save it as the value of a variable. Below is the example for the same –
Example Script:
var=$( ls /usr | wc -l )
echo Total $var entries on usr directory
Output of Command Substitution:
Total 13 entries on usr directory
In the above example, we have stored the result of ls /usr | wc -l , in a variable.
Below is the terminal shell depiction after executing the script –
Bash Script – Working of Bash Variables
A Bash script is a plain text file. This file contains different commands for step-by-step execution. These commands can be written directly into the command line but from a reusability perceptive it is useful to store all of the inter-related commands for a specific task in a single file. We can use that file for executing the set of commands one or more times as per our requirements. In programming, a variable is a value that can change, depending on conditions or on information passed to the program. A variable in bash can contain a number, a character, or a string of characters. Here in this article, we are going to discuss the working of variables within Bash Scripting.
Rules for defining variables in Bash Scripts are as follows –
- Variable names can contain uppercase, lowercase letters, numbers, underscores, and digits.
- It is a good practice to use uppercase letters for variable names within Bash scripts.
- Space is not allowed.
- Pre-defined keywords cannot be used. Like if, else, etc.
The simplest example of the use of variables in Bash scripting can be given as –
Example Script:
NAME="Satyajit Ghosh"
echo "His name is $NAME"
Output:
His name is Satyajit Ghosh
The above example shows a variable ‘name‘. Then it is used with an echo command to display its value. So, the basic syntax for writing variables within a Bash Script will be –
Syntax of Writing Variables:
VariableName=value
echo $VariableName #for accessing the value
If we want to change the value of a variable then we can do that. The basic syntax for that will be –
VariableName=value
VariableName=newValue
echo $VariableName #for accessing the value
Below is an example of the same –
Example Script:
AGE=10 #assigning a value
AGE=20 #changing the value
echo $AGE #display the value
Output:
20
Below is the terminal shell depiction after executing the script –