Basics of BASH. Part 2.
I apologize for such a long delay between 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 to the previous
article .
This part, as promised, will be devoted to cycles, mathematical operations and the use of external commands.
Let's start.
Cycles For-in loop
The for-in operator is intended to alternately refer to the values ​​listed in the list. Each value in the list is assigned to a variable.
The syntax is as follows:
for in _
do
done
Consider a small example:
#!/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 in the first 5 virtual consoles (terminals) a line will appear with its number. The variables from the list are alternately inserted into the variable $ i 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).
Operator syntax is as follows:
while
do
done
An example of how the cycle works is given in the following example:
#!/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 enter something other than “yes”. Between do and done, you can describe any structures, operators, etc., they will all be executed in a loop. But you should be careful with this loop, if you run a 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 conditional if-then-else statement, you can insert any expression or command that returns a return code, and the loop will be executed until the return code = 0! The operator "[" is an analogue of the test command, which checks the truth of the condition that was passed to it.
Consider another example, I took it from the book Advanced Bash Scripting. I really liked him :), but I simplified it a bit.
In this example, we will introduce another type of UNTIL-DO loop . This is almost a complete analogue of the WHILE-DO loop, only while some expression is false.
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"
Script execution result:
ite@ite-desktop:~$ ./bash2_primer3.sh
:
100
:
90
100 90 = 10
Mathematical 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 "
Result of performance:
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 can see, the list of mathematical operations is standard:
+ - addition
- - subtraction
* - multiplication
/ - division
** - exponentiation
% - module (division by module), remainder from division
let 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.
Work with external programs when writing shell scripts
First, some useful theory.
Redirect flows.
In bash (like many other shells) there are built-in file descriptors: 0 (stdin), 1 (stdout), 2 (stderr).
stdout - Standard output. This is where all the programs go.
stdin - Standard input. This is all that the user is typing in the console
stderr - Standard error output.
For operations with these descriptors, there are special characters:> (output redirection), <(input redirection). Operate them is not difficult. For example:
cat / dev / random> / dev / null
redirect the output of the cat / dev / random command to / dev / null (absolutely useless operation :))) or
ls -la> listing
write to the listing file the contents of the current directory (already useful)
If there is a need to add to the file (when using ">" it is replaced), it is necessary instead of ">" use ">>"
sudo <my_password
after asking sudo to enter a password, it will be taken from the file my_password, as if you typed it from the keyboard.
If you need to write to the file only errors that may have occurred while the program is running, you can use:
./program_with_error 2> error_file
the number 2 before the ">" means that you need to redirect everything that gets into the descriptor 2 (stderr).
If you need to force stderr to write to stdout, then you can trace it. in the following way:
./program_with_error 2> & 1
the symbol "&" means a pointer to the descriptor 1 (stdout)
(By default, stderr is writing to the console in which the user is working (he is writing to the display)).
2. Conveyors.
Conveyor is a very powerful tool for working with the Bash console. The syntax is simple:
1 | 2
1 | 2
- means that the output of command 1 will be passed to input to command 2
Conveyors can be grouped into 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 the lines in which the word hash occurs, and passes it 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 the need to process one command’s stdout and transfer to another command’s stdin, sometimes the result of one command must be processed in some way. In this section, I will try to explain the basic principles of working with external commands inside a script. I think that I have given enough examples and now you can write only the main points.
1. Transfer output to variable.
To write the output of a command to a variable, it is enough to enclose the command in `` quotes, for example
a = `echo "qwerty"`
echo $a
Work result: qwerty
However, if you want to write a list of directories into a variable, you must properly process the result to put the data into a 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 the directories in the / svn / folder using the svnadmin hotcopy command (which in our case has no meaning, just as an example). The most interesting is the line:
LIST=`find /svn/ -type d 2>/dev/null| awk '{FS="/"} {print $4}'| sort|uniq | tr '\n' ' '`
LIST=`find /svn/ -type d 2>/dev/null| awk '{FS="/"} {print $4}'| sort|uniq | tr '\n' ' '`
LIST=`find /svn/ -type d 2>/dev/null| awk '{FS="/"} {print $4}'| sort|uniq | tr '\n' ' '`
In it, the LIST variable is assigned to the execution of the find command processed by the awk, sort, uniq, tr commands (we will not discuss all these commands, for this is a separate article). In the LIST variable there will be the names of all the directories in the / svn / folder in one line (in order to set it on the loop.
As you can see, everything is not difficult, it is enough to understand the principle and write a couple of your scripts. In conclusion, I would like to wish you good luck in studying BASH and Linux in general. Criticism, as usual, is welcome. The next article may be devoted to the use of programs such as sed, awk.
Articles on
unix-admin.su