Shell scripting application - the preparation of shell script, shell variables

As more and more applications in the enterprise Linux systems, automated server management has become increasingly important. Automated maintenance of Linux servers, in addition to set up scheduled tasks, use Shell script is also a very important part. As a Linux system operation and maintenance engineers must have to master the basic knowledge and the preparation and use of Shell scripts.

shell script basis

In some complex Linux maintenance work, a large number of repetitive input and interaction not only time consuming, and error-prone, and write a Shell script just right, it can batch processing, automated completion of a series of maintenance tasks, greatly reducing administrator burden.

First, the preparation shell script

Shell scripts Linux system is a special application, it ranged between kernel and user operating system, acts as a role of "translator" is responsible for receiving user input operation instruction and explanation, the operation will be executed passed to the kernel executed, and outputs the result. Figure:
Shell scripting application (a)
Linux system, there are many common shell interpreter, when using a different shell script, its internal instructions, commands the warning lamp aspects there will be some differences.

[root @ localhost ~] # cat / etc / shells // view the current support system which shell 
* / bin / SH 
* / bin / bash 
* / sbin / nologin 
* / usr / bin / SH 
* / usr / bin / bash 
* / usr / sbin / nologin 
* / bin / tcsh 
* / bin / csh 
[the root @ localhost ~] # / bin / SH // switching the shell 
SH-4.2 # // return to the previous Exit the shell 
[the root @ localhost ~] #

/ Bin / bash is the default shell script currently used in most versions of Linux.

shell script: is simply put on the command line command executed sequentially stored in a text file, give it executable permissions. This text file can then be called a script. such as:

[root @ localhost ~] # cd / 
[root @ localhost /] # pwd 
/ // This is the result of two lives life output 
[root @ localhost ~] # vim a.sh // prepared for the file to. " sh "at the end just to let people know that this is a script. 
cd / 
pwd 
[root @ localhost ~] # chmod + // the X-a.sh service text file executable permissions 
[root @ localhost ~] # ./a.sh             
/ // view script execution results and execution of the command line The result is the same

Script execution method:

  1. "./" :( relative or absolute path) This method requires script must have executable rights;
  2. sh: by / bin / sh to interpret the script;
  3. or source. "": internal command to load the contents of the script.
    The first two methods are performed in sub-shell; third method is executed in the current shell!

Second, the operation of the pipeline and redirect

As the "batch processing," the special nature of shell scripts, mostly during its operation running in silent way, without user intervention. So learn to extract, filter execution information becomes very important.

1. redirection

A user through the operating system to process information in the process of interaction device file includes three types:
Shell scripting application (a)
standard input: data from the device receiving user input;
standard output: data output to the user through the device;
standard error: execution error report information through the apparatus .

Redirection types are divided into:
Shell scripting application (a)

2. Pipeline Operation

Action command is to pipe character output of the left, right command as a processing target. such as:

[the root @ localhost ~] # DF -ht | grep "/ $" | awk '{}. 6 Print $' 
26 is% 
// extract the root partition (/) in the disk usage information

Three, shell variables

Shell uses a variety of environments to the concept of "Tag". Shell used to store system variables and user-specific parameters need to be used (value), and these parameters may be changeable according to a user setting or a change in system environment. By proper use of variables, Shell program to provide more flexible functionality, and adaptable.

Linux system common four variables:

1. Custom Variables

Custom variables are variables defined by the user by the system it is only valid in the user's own Shell environment, and therefore, it was also known as local variables. In the preparation of Shell scripts, users usually set some specific custom variable to accommodate various changes during program execution, in order to meet different needs.

1) Define a new variable
basic format defined variable "variable name = variable value", equal on both sides does not allow spaces . Variable names need to start with a letter or an underscore, names do not contain special characters (for example:? +, -, *, /, ......, &,%, etc.). such as:

[root@localhost ~]# product=php
[root@localhost ~]# version=7.3.1

2) View and reference variables
are typically added leading "$" before the variable name, you can reference the value of a variable. such as:

[root@localhost ~]# echo $product
php
[root@localhost ~]# echo $product $version
php 7.3.1

When the variable name and easily confused with other characters immediately following one another, the need to use "{}" enclose the variable, or an error. such as:

[root @ localhost ~] # echo $ product1234 // did not find "product1234" This variable 
[root @ localhost ~] # echo $ {product} 1234 // correct output variables and character 
php1234

3) special operations variable assignment

1. double quotation marks ( ""): double quotes primarily as defining the role of the string, particularly when the content to be copied is contained in the space, must be enclosed in double quotes, double quotes may be omitted otherwise. such as:

[root @ localhost ~] # = Python 2.3.7 
bash: 2.3.7: command not found ... 
[root @ localhost ~] # = Python "Python 2.3.7" 
[root @ localhost ~] # echo $ Python 
Python 2.3.7

Double quotes is also allowed by the reference variable value $ other symbols, such as:

[root@localhost ~]# SQL="SQLServer $version"
[root@localhost ~]# echo $SQL
SQLServer 1.2.3

2. single quotes ( ''): Do not quote the value of other variables, $ treated as an ordinary character, single quotes special symbols will be considered ordinary characters, such as:

[root@localhost ~]# SQLServer='SQLserver $version'
[root@localhost ~]# echo $SQLServer
SQLserver $version

3. Anti-apostrophe (): mainly used in command substitution, variable screen allows you to perform the output of a command assigned to. Content anti-apostrophe must be enclosed command can be executed, otherwise it will go wrong. such as:

[root@localhost ~]# ls -lh `which systemctl`
-rwxr-xr-x. 1 root root 623K 11月  7 2016 /usr/bin/systemctl

Note: The use of anti-apostrophe difficult sub-ah command line replacement operation to implement nested command, then you can use the "$ ()" instead of anti-apostrophe operation, solve nesting problems. such as:

[root @ localhost ~] # $ -qc RPM (RPM -qf $ (Which useradd)) 
/ etc / default / useradd 
/etc/login.defs 
// query provider useradd command program packages installed configuration file location

4. braces ({}): for variables and character segmentation; if there are other characters in the variable, you need to use the "{}", {} is variable.

4) read command

read commands entered from the keyboard can make the content of variable assignment, such as:

[root @ localhost ~] # the Read abc 
/ opt / Backup // input value assigned to the variable abc 
[root @ localhost ~] # echo $ abc 
/ opt / Backup // View Results

In order to make the interface more user-friendly interactive operations, improve ease of use, read command to add "-p" option to set the message to inform the user what to enter content. such as:

[root @ localhost ~] # read -p " Please specify the directory stored:" abcd 
Please specify the directory stored in: / opt / Backup 
[root @ localhost ~] # echo $ ABCD 
/ opt / Backup

5) Set the variable scope of
the case, a new variable defined only valid in the current default Shell environment, so called local variables ; when entering a subroutine or a new Shell, local variables can not be used. such as:

[the root @ localhost ~] # echo "$ $ the SQL Version" 
SQLServer 1.2.3 1.2.3 
[the root @ localhost ~] # / bin / SH // Shell a switching environment 
sh-4.2 # echo "$ SQL $ version" / / no such variable 
sh-4.2 # exit // return a Shell 
[the root @ localhost ~] #

In order to make user-defined variables may continue to be used in all Shell environment, reduce duplication of work, you can export command by the internal variables specified export to global variables . You can specify the variable name as a parameter a plurality of (without using the "$" symbol), separated by spaces between variables can be!

[root @ localhost ~] # Export SQL Version 
[root @ localhost ~] # / bin / SH 
SH-4.2 # echo "$ SQL $ Version" 
SQLServer 1.2.3 1.2.3 
// test success

6) calculating the value of the variable
in the Bash Shell environment, only a simple integer arithmetic, decimal arithmetic is not supported. Numerical calculation is mainly performed through the internal command expr.
Commonly used variables:

  • Adder: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
  • Modulus (remainder) operator:%

such as:

[root@localhost ~]# x=35
[root@localhost ~]# y=16
[root@localhost ~]# expr $x + $y
51
[root@localhost ~]# expr $x - $y
19
[root@localhost ~]# expr $x \* $y
560
[root@localhost ~]# expr $x / $y
2                                                         //只取整数
[root@localhost ~]# expr $x % $y
3

2. Environment Variables

Environment variable refers to is running Linux system in advance by the need to create a good class variable. Value of the environment variables are automatically maintained by the Linux system, users will change with the state of change.
Use the env command to view all the current environment variables, in order to understand the purpose of each variable!
In the Linux system, environment variables global configuration file is / etc / profile, variables defined in the scope of this document to all users. Each user also has its own environment variable configuration file (~ / .bash_profile).

3. Position Variables

When the command line operations, the first field indicates the command word or a script, and the remaining string from left to right in order are sequentially assigned to the position variable.
Also called position location parameters, $ 1, $ 2 ... $ 8, $ 9 FIG. such as:

[root @ localhost ~] # vim 123.sh 
#! / bin / bash // declare what Shell use 
SUM = `expr $ 1 + $ 2` 
echo" $ 1 + $ 2 = $ SUM " 
[root @ localhost ~] # chmod + 123.sh X 
[the root @ localhost ~] # ./123.sh 12 34 // 12. 1 $, 34 $ 2 is 
12 + 34 = 46

4. predefined variables

Predefined variable is predefined by a program Bash preferred class of special variables can not be modified, the format of predefined variables:

  • $ #: The number of command line variable position
  • $ *: The contents of all position variables
  • A command execution status return $ ?: post, when the return value of 0 indicates the state of performing the normal, non-zero value indicates an error or abnormality
  • $ 0: currently executing process / program name

Write them commands in the script, you should at the command line, after the execution is completed to confirm the results, and then write the script. The first written script, can make life difficult, when writing the script completes later have similar needs, the script can be run directly!

Guess you like

Origin www.linuxidc.com/Linux/2019-08/160118.htm