You get a bonus - 1 coin for daily activity. Now you have 1 coin

21 - the basics of bash programming

Lecture



In this lecture, we will begin to get acquainted with the basic language constructs of bash . Knowledge of the bash language is necessary both to study the operation of the operating system (most of the scripts are written in bash ) and to write your own scripts.

You already know that the script must be an executable file and begin with the line #! / Bin / bash . Except the case #! The # (“Sharp”) icon is the beginning of a comment. Lines that begin with the # character will be skipped by the interpreter when processing the script:

#! / bin / bash
# This is a comment
# This is also a comment

Variables

The variable name in bash must begin with a letter. Then you can use numbers. In bash, variables have no type, so you do not need to declare a variable first, but you can immediately assign a value:


#! / bin / bash
# Variable
S1 = Hello!
S2 = "Hello World!"

If a variable is assigned a string containing spaces (or other special characters), then it must be entered in double quotes, otherwise there will be an error. Also note that there must be no spaces around the = sign.

  21 - the basics of bash programming

  21 - the basics of bash programming

To access the contents of a variable, a $ character is placed in front of the variable name:

echo $ S1
echo $ s2

In this case, a substitution operation will be performed. First, the $ S2 construction will be replaced with Hello World , and then the *** will be executed *** and echo Hello World . The substitution operation can be performed not only in the case of the echo command, but also in other com *** ahs, for example com *** ah comparison. In this case, it is recommended to take the $ S1 construct in double quotes - “$ S1 ″ . Later we will take a closer look at why. As a substitution can be used and the result of the command. The syntax is similar - we write the $ character, and then a com *** *** in parentheses without spaces. For example: OF = / var / backup - $ (date +% Y% m% d) .tgz . In this example, the com *** will be executed first and the date +% Y% m% d in parentheses, the result of which will be the current date in the format YYYYMMDD (for example 20091217). Then, a stand will be executed to form the string /var/backup-20091217.tgz and then this string will be assigned to the variable OF .

Do not forget that if there were any spaces in the string, then the whole construct should be enclosed in double quotes: OF = ”/ var / backup $ (date +% Y% m% d) .tgz” .

Variables can be local and global. Global we discussed above, and local are described using the word local . Consider the following example:

one
2
3
four
five
6
7
eight
9

#! / bin / bash
STR = Hello
function echoworld {
local STR = World
echo $ STR
}
echo $ STR
echoworld
echo $ STR

The result of the command will be as follows:

Hello
World
Hello

We'll talk about features later. Now the main focus is on the fact that although the output to the screen is carried out by the same comma *** th echo and the same STR variable, the output result is different. Since the local variable was declared in the body of the function, and when accessing it, a local value will be output from the function. If the output comes from the body of the script, then the initially specified global value of the variable is output.

If construct

To check the conditions in the script, use the if construct. The general syntax of the if construct in simplified form is as follows:
if [condition]; then
command block
else
command block
fi

Key design elements are if, then, else, fi . A semicolon is needed only if there is more than one key element of the if construct on one line. If each key element is located on a new line, then a semicolon is not needed. Consider the following practical example:

#! / bin / bash
STR = "Hello world"
if [$ STR = "Hello world"]
then
echo yes
else
echo NO
fi

In the example above there is an error. At the beginning of the lecture, I mentioned that in comparison operations it is desirable to enclose $ STR in quotes. In our case, as a result of the first substitution, we get the following:

[Hello world = "Hello world"]

The operation logic [] is as follows: After the opening bracket [ a space is required (first), then to the next space (second), the first value to be compared, then a comparison operator (for example = ), then a space (third) and from it to the next space (fourth) second compared value. Immediately after the fourth space, the closing bracket ] . We also succeeded in violating this rule as a result of the fact that there are gaps in the STR variable. If you enclose $ STR in double quotes “$ STR” then there will be no error. Correct the script and check.

The comparison construct [] produces as a result a number: 0 - if the condition is true, and non-zero, if it is incorrect. If the result is zero, then commands from then to the next key construct will be executed, if the result is nonzero, then a block of commands from else will be executed to the next key construct. By the way, the [] construct can be used not only in if , but also separately, then we will consider similar examples. I also want to note that [] is a newer design and has an older version, which is also often found in scripts. This is a *** *** test . The if [$ STR = "Hello world"] string can be written like this: if test $ STR = “Hello world” .

To see the built-in help about the if construct, you need to type help if in the interpreter. Then a brief syntax reference will be displayed. Fully syntax is as follows:

if COMMANDS; then COMMANDS; [elif COMMANDS; then COMMANDS; ] ... [else COMMANDS; ] fi

Thus, there is another key element - elif . I propose to self-disassemble this option and create your own test bash script using elif .

The if construct from the example can be written on the command line and executed interactively. The line will look like this:

STR = "Hello world"; if ["$ STR" = "Hello world"]; then echo YES; else echo NO; fi

As in the script, but there are semicolons that separate commands and key elements. Once again I draw attention to the spaces in [] . In order not to forget about this, remember that [ this is just a comma *** a (like any other linux command), and after the command there is always a space followed by keys or parameters.

Comparison operators

Since we are talking about the comparison construct ( [] or test ), then it's time to get acquainted with the bash language comparison operators. With one of them have already met - this is = . Consider the others.

Comparison operators in bash are arithmetic (for comparing numbers) and string comparison operators.
Arithmetic operators consist of two characters in front of which is a hyphen. Below are the arithmetic operators and their analogy from C in brackets.

-lt - less then - less (<)
-gt - greater then - more (>)
-le - less or equal - less than or equal (<=)
-ge - greater or equal - greater than or equal (> =)
-eq - equal - equal (==)
-ne - not equal - not equal (! =)

If you are familiar with the English language, then it will be easy to remember.

Line comparison operators are easier to remember.

STR1 = STR2 - equal to
STR1! = STR2 - not equal
STR1 - less
STR1> STR2 - more
-n STR 1 - returns 0 if the string is non-zero (has at least one character)
-z STR1 - returns 0 if the string is zero length.

A practical example. Type and execute the following line in the console (do not forget about the spaces!):

STR1 = aaa; STR2 = abc; ["$ STR1" = "$ STR2"]; echo $?

As a result, you get the number 1, which will output a com *** and echo $? . The construction of $? contains the numeric result of the previous command. The previous com *** a was ["$ STR1" = "$ STR2"] if the com condition *** met and returned 0, but since the condition is not met, the result of the command execution is non-zero.

In conclusion, a few words about the operation of checking the file. In almost every system script, you will find a construct like [-a / etc / filename] or [-f "$ file"] , where file is a variable containing the name of the file. This is an operation to check a file or file properties. The name of the file is used as a parameter in the command.

[-f "file name"] - returns 0 if the file exists and it is a regular file
[-e "file name"] - returns 0 if the file exists
[-w "file name"] - returns 0 if the file exists and has write access to it.

For other file scan options, see the man bash help in the CONDITIONAL EXPRESSIONS section.

created: 2014-09-13
updated: 2021-03-13
132488



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

LINUX operating system

Terms: LINUX operating system