Using variables in linux bash

Bash Beginner Series #2: Understanding Variables in Bash Shell Scripting

In the second entry of the bash beginner series, learn about using variables in your bash shell scripts.

Time changes, and so do variables!

You must have played with variables quite a bit if you did any sort of programming.

If you never worked with variables before, you can think of them as a container that stores a piece of information that can vary over time.

Variables always come in handy while writing a bash script and in this tutorial, you will learn how to use variables in your bash scripts.

Using variables in bash shell scripts

In the last tutorial in this series, you learned to write a hello world program in bash.

That was a simple Hello World script. Let’s make it a better Hello World.

Let’s improve this script by using shell variables so that it greets users with their names. Edit your hello.sh script and use read command to get input from the user:

#! /bin/bash echo "What's your name, stranger?" read name echo "Hello, $name"

Now if you run your hello.sh script; it will prompt you for your name and then it will greet you with whatever name you provide to it:

[email protected]:~/scripts$ ./hello.sh What's your name, stranger? Elliot Hello, Elliot

In the above example, I entered Elliot as my name and then the script greeted me with “Hello, Elliot”. That’s definitely much better than a generic “Hello, World” program. Don’t you agree?

Variables in shell script

Step by step explanation of the above shell script

Now let’s go over the script line by line here to make sure that you understand everything.

I first included the shebang line to explicitly state that we are going to use bash shell to run this script.

Next, I ask the user to enter his/her name:

echo "What's your name, stranger?"

That’s just a simple echo command to print a line to the terminal; pretty self-explanatory.

Now here’s the line where all the magic happens:

Here, I used the read command to transfer the control from running script to the user, so that the user can enter a name and then store whatever user entered, in the ‘name’ variable.

Читайте также:  Add user in linux with home directory

Finally, the script greets the user with their name:

Notice here, you have to precede the variable name with a dollar sign to get the value stored in the variable name. If you omit the dollar sign, “Hello, name” would be displayed instead.

Integers, strings or characters? How to create different variable data types in bash shell?

Let’s mess around a little bit more with the variables.

You can use the equal sign to create and set the value of a variable. For example, the following line will create a variable named age and will set its value to 27.

After you have created the age variable, you can change its value as much as you want.

The above command changes the value of the variable age from 27 to 3. If only times can go back, I can hear you saying!

Variables can hold different types of data; variables can store integers, strings, and characters.

letter=’c’ color=’blue’ year=2020

Constant variables in bash shell

You can also create a constant variable, that is to say, a variable whose value will never change! This can be done by preceding your variable name with the readonly command:

The above command will create a constant variable PI and set its value of 3.14159. Now, you can’t’ change the value of constant variable, if you try, you will get an error:

bash: PI: readonly variable

As you can see, you can only read the value of a constant variable, but you can never change its value after it is created.

Constant Variable in Bash Shell

Command substitutions

The ability to store the output of a command into a variable is called command substitution and it’s by far one of the most amazing features of bash.

The date command is a classic example to demonstrate command substitution:

The above command will store the output of the command date into the variable TODAY. Notice, how you need to enclose the date command within a pair of parentheses and a dollar sign (on the left).

Command substitution in Bash shell

Alternatively, you can also enclose the command within a pair of back quotes:

The back quote method is the old way of doing command substitution, and so I highly recommend that you avoid it and stick with the modern approach:

Before you go, try turning Hello World script to a smart HelloWorld script

Now since you just learned how to do command substitution, it would make sense to visit the Hello World script one last time to perfect it!

Last time, you asked the user to enter his/her name so the script greets them; this time, you are not going to ask, your script already knows it!

Use the whoami command along with command substitution to greet whoever run the script:

#! /bin/bash echo "Hello, $(whoami)"

As you can see, you only needed just two lines! Now run the script:

Using command substitution in bash shell script

Alright, this brings us to the end of this tutorial. You may practice what you just learned by solving the problems and refer to their solutions if you get stuck or need a hint.

Читайте также:  Certificate installation in linux

I hope you have enjoyed working with shell variables as much as me. Check out the next chapter in this series, where I discuss how you can pass arguments to your shell scripts.

Источник

How to use Variables in Bash Programming

Variables work as temporary storage for any programming language. The coder needs to have a clear concept of using different variables in the code. Variables are used to store specific data. The most commonly used data type of variables are integer, string, float, double and Boolean. The data type of any variable has to be defined at the time of variable declaration for strongly type programming languages. But BASH is a weakly typed programming language that does not require to define any data type at the time of variable declaration. So when any numeric value assigns to a variable then it will work as integer and when any text value assigns to a variable then it is string. BASH variables can be used from terminal or on any BASH file. The use of different types of BASH variables are described in this tutorial by using many examples.

Using variable from command line or terminal

You don’t have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use ‘$’ symbol before the variable name when you want to read data from the variable. You can set and get data from a variable from the terminal in the following way.

Example-1: Declaring and reading string data using variable

Run the following commands from the terminal.

Variables Bash Programming

Example-2: Combining two string variables

You don’t have to use any operator to combine two or more strings like other languages. Here, $var1 is used to store string value and $var2 is used to store a numeric value. Run the following commands from the terminal to combine two variables $var1 and $var2.

**Note: You can print the value of the variable without any quotation but if you use quotations then you have to use double quotations.

Example-3: Concatenating strings with variables

Double quotation can be used to read the value of the variable. In this example, single quotation is used on one echo statement and double quotation is used on another echo statement. Run the following commands from the terminal to check the output.

Example-4: Declaring and reading numeric data using variables

One of the major limitations of Bash programming is that it can’t perform arithmetic operations like other programming languages. Numeric values are taken as strings in BASH. So no arithmetic operation can be done by normal expression and it just combines the numeric values. If you write the expression with double first bracket then the arithmetic operation works properly. Run the following commands from the terminal.

Читайте также:  Vbox guest additions iso linux

Example-5: Doing arithmetic operation using bc command

bc command is another way to do arithmetic operation in BASH. Run the following commands from the terminal. When you use bc command only for doing any arithmetic operation then fractional parts are omitted from the result. You have to use -l option with bc command to get the result with fractional value.

Using variables in bash file

You can define variable in bash file by the same way which are mentioned in above examples. You have to create file with .sh or .bash extension to run bash script.

Example-6: Creating simple bash script

Copy the following code in a text editor and save the file with bash extension. In this script, one string and one numeric variables are declared.

str = «Learn BASH Programming»

#print string value
echo $str

#subtract 20 from numeric variable
( ( result = $num — 20 ) )

#print numeric value
echo $result

Example-7: Using global and local variables

In the following script, one global variable n and two local variables n and m are used.
When the function addition() is called then the value of the local variable n is taken for calculation but global variable n remains unchanged.

#!/bin/bash
n = 5
function addition ( )
{
local n = 6
local m = 4
( ( n =n+m ) )
echo $n

Example-8: Using array variable

Array variable is used to store a list of data. The following example shows how you use of array variable in bash script. The elements of any array are separated by space in BASH. Here, an array of 6 elements is declared. There is no built-in function or property to count the total elements of the array. # with * is used to count total elements. All elements are indicated by *. For loop is used here to iterate the array values. Reading array values and array values with key are shown in the next part of this script.

myarr = ( HTML JavaScript PHP jQuery AngularJS CodeIgniter )

#Count total number of elements of the array
total = $
echo «Total elements: $total «

#Print each element value of the array
echo «Array values :»
for val in $
do
printf » %s \n » $val
done

#Print each element value of the array with key

echo «Array values with key:»
for key in $
do
printf «%4d: %s \n » $key $
done

To use BASH variables properly you need a clear concept on the declaration and use of variables. This tutorial will help you to get a clear idea on BASH variables. After exercising the above examples properly you will be able to use variables more efficiently in your bash scripts.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

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