Use variables in linux bash

Bash — Using Variables¶

In this chapter you will learn how to use variables in your bash scripts.

Objectives: In this chapter you will learn how to:

Store information for later use;
Delete and lock variables;
Use environment variables;
Substitute commands;

linux, script, bash, variable

Knowledge:
Complexity:

Reading time: 10 minutes

Storing information for later use¶

As in any programming language, the shell script uses variables. They are used to store information in memory to be reused as needed during the script.

A variable is created when it receives its content. It remains valid until the end of the execution of the script or at the explicit request of the script author. Since the script is executed sequentially from start to finish, it is impossible to call a variable before it is created.

The content of a variable can be changed during the script, as the variable continues to exist until the script ends. If the content is deleted, the variable remains active but contains nothing.

The notion of a variable type in a shell script is possible but is very rarely used. The content of a variable is always a character or a string.

#!/usr/bin/env bash # # Author : Rocky Documentation Team # Date: March 2022 # Version 1.0.0: Save in /root the files passwd, shadow, group, and gshadow # # Global variables FILE1=/etc/passwd FILE2=/etc/shadow FILE3=/etc/group FILE4=/etc/gshadow # Destination folder DESTINATION=/root # Clear the screen clear # Launch the backup echo "Starting the backup of $FILE1, $FILE2, $FILE3, $FILE4 to $DESTINATION:" cp $FILE1 $FILE2 $FILE3 $FILE4 $DESTINATION echo "Backup ended!" 

This script makes use of variables. The name of a variable must start with a letter but can contain any sequence of letters or numbers. Except for the underscore «_», special characters cannot be used.

By convention, variables created by a user have a name in lower case. This name must be chosen with care so as not to be too evasive or too complicated. However, a variable can be named with upper case letters, as in this case, if it is a global variable that should not be modified by the program.

The character = assigns content to a variable:

variable=value rep_name="/home" 

There is no space before or after the = sign.

Once the variable is created, it can be used by prefixing it with a dollar $.

It is strongly recommended to protect variables with quotes, as in this example below:

file=file name touch $file touch "$file" 

As the content of the variable contains a space, the first touch will create 2 files while the second touch will create a file whose name will contain a space.

To isolate the name of the variable from the rest of the text, you must use quotes or braces:

file=file_name touch "$file"1 touch $1 

The systematic use of braces is recommended.

The use of apostrophes inhibits the interpretation of special characters.

message="Hello" echo "This is the content of the variable message: $message" Here is the content of the variable message: Hello echo 'Here is the content of the variable message: $message' Here is the content of the variable message: $message 

Delete and lock variables¶

The unset command allows for the deletion of a variable.

name="NAME" firstname="Firstname" echo "$name $firstname" NAME Firstname unset firstname echo "$name $firstname" NAME 

The readonly or typeset -r command locks a variable.

name="NAME" readonly name name="OTHER NAME" bash: name: read-only variable unset name bash: name: read-only variable 

A set -u at the beginning of the script will stop the execution of the script if undeclared variables are used.

Читайте также:  Отличия linux от freebsd

Use environment variables¶

Environment variables and system variables are variables used by the system for its operation. By convention these are named with capital letters.

Like all variables, they can be displayed when a script is executed. Even if this is strongly discouraged, they can also be modified.

The env command displays all the environment variables used.

The set command displays all used system variables.

Among the dozens of environment variables, several are of interest to be used in a shell script:

Variables Description
HOSTNAME Host name of the machine.
USER , USERNAME and LOGNAME Name of the user connected to the session.
PATH Path to find the commands.
PWD Current directory, updated each time the cd command is executed.
HOME Login directory.
$$ Process id of the script execution.
$? Return code of the last command executed.

The export command allows you to export a variable.

A variable is only valid in the environment of the shell script process. In order for the child processes of the script to know the variables and their contents, they must be exported.

The modification of a variable exported in a child process cannot be traced back to the parent process.

Without any option, the export command displays the name and values of the exported variables in the environment.

Substitute commands¶

It is possible to store the result of a command in a variable.

This operation is only valid for commands that return a message at the end of their execution.

The syntax for sub-executing a command is as follows:

variable=`command` variable=$(command) # Preferred syntax 

With everything we’ve just seen, our backup script might look like this:

#!/usr/bin/env bash # # Author : Rocky Documentation Team # Date: March 2022 # Version 1.0.0: Save in /root the files passwd, shadow, group, and gshadow # Version 1.0.1: Adding what we learned about variables # # Global variables FILE1=/etc/passwd FILE2=/etc/shadow FILE3=/etc/group FILE4=/etc/gshadow # Destination folder DESTINATION=/root ## Readonly variables readonly FILE1 FILE2 FILE3 FILE4 DESTINATION # A folder name with the day's number dir="backup-$(date +%j)" # Clear the screen clear # Launch the backup echo "****************************************************************" echo " Backup Script - Backup on $ " echo "****************************************************************" echo "The backup will be made in the folder $." echo "Creating the directory. " mkdir -p $/$ echo "Starting the backup of $, $, $, $ to $/$:" cp $ $ $ $ $/$ echo "Backup ended!" # The backup is noted in the system event log: logger "Backup of system files by $ on $ in the folder $/$." 

Running our backup script:

**************************************************************** Backup Script - Backup on desktop **************************************************************** The backup will be made in the folder backup-088. Creating the directory. Starting the backup of /etc/passwd, /etc/shadow, /etc/group, /etc/gshadow to /root/backup-088: Backup ended! 

Contributors: Steven Spencer

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

Источник

How to Use Variables in Shell Scripting

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

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.

Читайте также:  Oracle virtualbox установить linux mint

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