I want to declare a variable for a bash program but I don’t know about it so can anyone help me?
How to declare variables in bash?
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Bash scripts allows variable declaration as well as constant definition. There are two ways to declare a variable. The easiest is as follows:
Notice that there is no space between the variable name, the equal sign and the content of the variable. When we use this method for declaring variables, the content of the variable can be a string or an integer. In other words, it is not a typed variable.
When you want to refer to the content of a variable, like when you write it on the screen, you just have to put a dollar sign in front of the variable name.
But if you want to do some operations other than displaying the value of a variable like performing a sum or concatenation you don’t have to use the dollar sign. You just have to use the variable names. If you find this confusing you can use the following rule of thumb. If you are writing a script and need to refer to the value of a variable and not to the variable itself just put a dollar sign in front of it.
Take a look at the next example when I am creating a script with one string variable and one integer variable, then I echo both variables.
MyVariable=”I will do some math!: ”
echo $MyVariable $Number + $Number = $((Number + Number))
The last line of the code may look complex, but it is not. Starting from left to right the “+” and the “=” signs are considered as text. The echo command echoes characters not variables. Remember the rule of thumb I told you? By putting the dollar sign I am referring to the text value of the variables. The other part of the statement, $((Number + Number)), pay close attention to the parenthesis. Parentheses are always evaluated from the inner to the outmost, a basic rule of algebra. The first parenthesis is (Number + Number), notice that Number is not preceded by a dollar sign. So according to the rule of thumb, we are referring to the variable Number and not to its content. Since the Number variable is numeric, we are doing a sum. Now the outer most parenthesis is preceded by a dollar sign so we are referring to the value of the expression (Number + Number).
I created a graphic to show what that line does.
This is an easy way to understand the code.
On the next screen capture you will see the output of the previous script execution.
This is the output of the sample script.