Linux shell variables in script

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.

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.

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 Shell Scripting

In this post, we will discuss how to use variables in bash shell scripting with examples.

Читайте также:  Astra linux запуск консоли

In every programming language variables plays an important role , in Linux shell scripting we can use two types of variables : System Defined Variables & User Defined Variables.

A variable in a shell script is a means of referencing a numeric or character value. And unlike formal programming languages, a shell script doesn’t require you to declare a type for your variables

System Defined Variables

These are the variables which are created and maintained by Operating System(Linux) itself. Generally these variables are defined in CAPITAL LETTERS. We can see these variables by using the command “$ set“. Some of the system defined variables are given below :

Linux-Shell-Variables-Meanings

To print the value of above variables, use echo command as shown below :

$ echo $HOME /home/linuxtechi $ echo $USER linuxtechi $

We can use environment variables in our bash scripts by using the environment variable’s name preceded by a dollar sign. Example is shown below,

$ cat myscript #!/bin/bash # display user information from the system. echo "User info for userid: $USER" echo UID: $UID echo HOME: $HOME

Notice that the environment variables in the echo commands are replaced by their current values when the script is run. Also notice that we were able to place the $USER system variable within the double quotation marks in the first string, and the shell script was still able to figure out what we meant. There is a drawback to using this method, however. Look at what happens in this example:

$ echo "The cost of the item is $15" The cost of the item is 5 $

That is obviously not what was intended. Whenever the script sees a dollar sign within quotes, it assumes you’re referencing a variable. In this example the script attempted to display the variable $1 (which was not defined), and then the number 5. To display an actual dollar sign, you must precede it with a backslash character:

$ echo "The cost of the item is \$15" The cost of the item is $15 $

That’s better. The backslash allowed the shell script to interpret the dollar sign as an actual dollar sign, and not a variable.

User Defined Variables

These variables are defined by users. A shell script allows us to set and use our own variables within the script. Setting variables allows you to temporarily store data and use it throughout the script, making the shell script more like a real computer program.

User variables can be any text string of up to 20 letters, digits, or an underscore character. User variables are case sensitive, so the variable Var1 is different from the variable var1. This little rule often gets novice script programmers in trouble.

Values are assigned to user variables using an equal sign. No spaces can appear between the variable, the equal sign, and the value (another trouble spot for novices). Here are a few examples of assigning values to user variables:

var1=10 var2=-57 var3=testing var4="still more testing"

The shell script automatically determines the data type used for the variable value. Variables defined within the shell script maintain their values throughout the life of the shell script but are deleted when the shell script completes.

Читайте также:  Linux запуск приложения от имени другого пользователя

Just like system variables, user variables can be referenced using the dollar sign:

$ cat test3 #!/bin/bash # testing variables days=10 guest="Katie" echo "$guest checked in $days days ago" days=5 guest="Jessica" echo "$guest checked in $days days ago" $

Running the script produces the following output,

$ chmod u+x test3 $ ./test3 Katie checked in 10 days ago Jessica checked in 5 days ago $

Each time the variable is referenced, it produces the value currently assigned to it. It’s important to remember that when referencing a variable value you use the dollar sign, but when referencing the variable to assign a value to it, you do not use the dollar sign. Here’s an example of what I mean:

$ cat test4 #!/bin/bash # assigning a variable value to another variable value1=10 value2=$value1 echo The resulting value is $value2 $

When you use the value of the value1 variable in the assignment statement, you must still use the dollar sign. This code produces the following output:

$ chmod u+x test4 $ ./test4 The resulting value is 10 $

If you forget the dollar sign, and make the value2 assignment line look like:

value2=value1 you get the following output: $ ./test4 The resulting value is value1 $

Without the dollar sign the shell interprets the variable name as a normal text string, which is most likely not what you wanted.

Use of Backtick symbol (`) in shell variables

The backtick allows you to assign the output of a shell command to a variable. While this doesn’t seem like much, it is a major building block in script programming. You must surround the entire command line command with backtick characters:

The shell runs the command within the backticks and assigns the output to the variable testing. Here’s an example of creating a variable using the output from a normal shell command:

$ cat test5 #!/bin/bash # using the backtick character testing=`date` echo "The date and time are: " $testing $

The variable testing receives the output from the date command, and it is used in the echo statement to display it. Running the shell script produces the following output:

$ chmod u+x test5 $ ./test5 The date and time are: Tue 4 Oct 05:20:44 BST 2022 $

Note : In bash you can also use the alternative $(…) syntax in place of backtick (`),which has the advantage of being re-entrant.

$ echo " Today’s date & time is :" $(date) Today’s date & time is : Tue 4 Oct 05:21:51 BST 2022 $

That’s all from this post, I hope you have learned how to use variables in bash shell scripting. Please do post your queries and feedback in below comments section.

2 thoughts on “How to Use Variables in Shell Scripting”

Thanks Pradeep, Very good article. Question – what is the best way to set variables deep within functions or loops so that the variable can be used after the function completes by other code below the function or loop? I have used system level variables but that means anyone can access them. Is there another way? Reply

Источник

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