Basics of BASH. Part 2

  • Tutorial
Basics of BASH. Part 2. I
apologize for such a big delay between the articles, but the session makes itself felt at the most inopportune moment :)
Thank you all for the comments, criticism and additions that were voiced in the comments on the previous article .
This part, as promised, will be devoted to cycles, mathematical operations and the use of external commands.
Let's get started.


Cycles. For-in loop


The for-in operator is used to access the values ​​listed in the list one by one. Each value in the list is assigned to a variable.
The syntax is as follows: Consider a small example:
for переменная in список_значений
do
команды
done


#!/bin/bash
for i in 0 1 2 3 4 #переменной $i будем поочередно присваивать значения от 0 до 4 включительно
do
echo "Console number is $i" >> /dev/pts/$i #Пишем в файл /dev/pts/$i(файл виртуального терминала) строку "Console number is $i"
done #цикл окончен
exit 0

After executing the example, a line with its number will appear in the first 5 virtual consoles (terminals). The values ​​from the list are substituted into the variable $ i one by one and the loop is working with the value of this variable

Cycles. While loop.


The while loop is more complex than the for-in loop and is used to repeat commands while some expression is true (return code = 0).
The syntax of the operator is as follows: We consider an example of a loop operation using the following example:
while выражение или команда возвращающая код возврата
do
команды
done


#!/bin/bash
again=yes #присваиваем значение "yes" переменной again
while [ "$again" = "yes" ] #Будем выполнять цикл, пока $again будет равно "yes"
do
echo "Please enter a name:"
read name
echo "The name you entered is $name"

echo "Do you wish to continue?"
read again
done
echo "Bye-Bye"

And now the result of the script:
ite@ite-desktop:~$ ./bash2_primer1.sh
Please enter a name:
ite
The name you entered is ite
Do you wish to continue?
yes
Please enter a name:
mihail
The name you entered is mihail
Do you wish to continue?
no
Bye-Bye


As you can see, the loop is executed until we introduce something other than “yes”. Between do and done, you can describe any structures, operators, etc., all of them will be executed in a loop. But you should be careful with this loop if you run any command in it, without changing the expression variable, you can get into an endless loop.
Now about the condition of truth. After while, as in the if-then-else conditional statement, you can insert any expression or command that returns a return code, and the loop will be executed as long as the return code = 0! The operator "[" is an analogue of the test command, which checks the validity of the condition that was passed to it.

Consider another example, I took it from the book Advanced Bash Scripting. I really liked it :), but I simplified it a bit.In this example, we will introduce another type of UNTIL-DO loop . This is an almost complete analogue of the WHILE-DO cycle, only some expression is being executed so far.
Here is an example:
#!/bin/bash
echo "Введите числитель: "
read dividend
echo "Введите знаменатель: "
read divisor

dnd=$dividend #мы будем изменять переменные dividend и divisor,
#сохраним их знания в других переменных, т.к. они нам
#понадобятся
dvs=$divisor
remainder=1

until [ "$remainder" -eq 0 ]
do
let "remainder = dividend % divisor"
dividend=$divisor
divisor=$remainder
done

echo "НОД чисел $dnd и $dvs = $dividend"

The result of the script:
ite@ite-desktop:~$ ./bash2_primer3.sh
Введите числитель:
100
Введите знаменатель:
90
НОД чисел 100 и 90 = 10


Math operations


Let command.
The let command performs arithmetic operations on numbers and variables.
Consider a small example in which we perform some calculations on the numbers entered:
#!/bin/bash
echo "Введите a: "
read a
echo "Введите b: "
read b

let "c = a + b" #сложение
echo "a+b= $c"
let "c = a / b" #деление
echo "a/b= $c"
let "c <<= 2" #сдвигает c на 2 разряда влево
echo "c после сдвига на 2 разряда: $c"
let "c = a % b" # находит остаток от деления a на b
echo "$a / $b. остаток: $c "

Execution Result:
ite@ite-desktop:~$ ./bash2_primer2.sh
Введите a:
123
Введите b:
12
a+b= 135
a/b= 10
c после сдвига на 2 разряда: 40
123 / 12. остаток: 3

Well, as you see, nothing complicated, the list of mathematical operations is standard:
+ - addition
- - subtraction
* - multiplication
/ - division
** - raising to the power
% - module (modulo division), the remainder of
let division allows you to use abbreviations of arithmetic commands, thereby reducing the number of variables used. For example: a = a + b is equivalent to a + = b, etc.

Working with external programs when writing shell scripts


First, a little useful theory.
Redirection of flows.

In bash (like many other shells) there are built-in file descriptors: 0 (stdin), 1 (stdout), 2 (stderr).
stdout - Standard output. Everything that
stdin programs output here is standard input. This is all that the user types in the
stderr console - Standard error output.
For operations with these descriptors, there are special characters:> (output redirection), <(input redirection). It is not difficult to operate with them. For instance:
cat / dev / random> / dev / null
redirect the output of cat / dev / random to / dev / null (absolutely useless operation :))) or
ls -la> listing
write the contents of the current directory to the listing file (already more useful)
If you need to append to the file (when using ">" it is replaced), you must use ">>" instead of ">"
sudo <my_password
after sudo's request for a password, it will be taken from the my_password file, as if you entered it from the keyboard.
If it is necessary to write to the file only errors that might have occurred during program operation, then you can use:
./program_with_error 2> error_file
the number 2 before ">" means that you need to redirect everything that falls into handle 2 (stderr).
If you need to force stderr to write to stdout, then you can trace this. way:
./program_with_error 2> & 1
the "&" symbol means a pointer to handle 1 (stdout)
(By default, stderr writes to the console the user is working in (writes to the display earlier)).

2. Conveyors.

The pipeline is a very powerful tool for working with the Bash console. The syntax is simple:
команда1 | команда 2 - means that the output of command 1 will be passed to the input of command 2.
Conveyors can be grouped in chains and output using redirection to a file, for example:
ls -la | grep "hash" | sort> sortilg_list
the output of the ls -la command is passed to the grep command, which selects all lines containing the hash word, and passes the sort command to the sort command, which writes the result to the sorting_list file. Everything is pretty clear and simple.

Most often, Bash scripts are used to automate some routine operations in the console, hence sometimes it becomes necessary to process the stdout of one command and transfer it to stdin to another command, while the result of executing one command must be handled in some way. In this section, I will try to explain the basic principles of working with external commands inside the script. I think that I have given enough examples and now we can write only the main points.

1. Passing output to a variable.

In order to write the output of a command into a variable, it is enough to enclose the command in quotation marks, for example
a = `echo "qwerty"`
echo $a

Work Result: qwerty

However, if you want to write a list of directories to a variable, then you need to properly process the result to put the data in the variable. Consider a small example:
LIST=`find /svn/ -type d 2>/dev/null| awk '{FS="/"} {print $4}'| sort|uniq | tr '\n' ' '`
for ONE_OF_LIST in $LIST
do
svnadmin hotcopy /svn/$ONE_OF_LIST /svn/temp4backup/$ONE_OF_LIST
done

Here we use the for-do-done loop to archive all directories in the / svn / folder using the svnadmin hotcopy command (which in our case does not matter to anyone, just as an example). The line is most interesting: LIST=`find /svn/ -type d 2>/dev/null| awk '{FS="/"} {print $4}'| sort|uniq | tr '\n' ' '`In it, the LIST variable is assigned the execution of the find command processed by the awk, sort, uniq, tr commands (we will not consider all these commands, because this is a separate article). The LIST variable will contain the names of all directories in the / svn / folder located on one line (in order to erase it from the cycle.

As you can see, everything is not difficult, just understand the principle and write a couple of your scripts. In conclusion, I want to wish you good luck in learning BASH and Linux in general. The criticism is welcome as usual. The following article might be dedicated to the use of programs such as sed, awk.

articlesunix-admin.su

Also popular now: