Shell script Basics

Bowen catalogue
I. Shell script Foundation
Redirection and pipeline operation
3. Use Shell variable

I. Shell script Foundation

Shell script in Linux system is a special application program, which is between the kernel and the user of the operating system. It acts as a "command interpreter". It is responsible for receiving and interpreting the operation command input by the user, passing the operation to be executed to the kernel, and outputting the execution result.

1. Simply write Shell script

[root@centos01 ~]# VIM aaa.sh <! -- new aaa.sh file -- >
#!/bin/bash
#Description E-Mail:2807489749@qq.com BY:LYX
cd /boot/
echo "Show current directory:"
pwd
echo "View to vml Starting file:"
ls -lh vml*
[root@centos01 ~]# Chmod + X AAA. Sh <! -- add executable permission -- >

In the above aaa.sh script file, the first line of "ා / bin/bash" is a special script declaration, which means that statements after this line will be interpreted and executed through the / bin/bash program; other statements beginning with "ා" represent comment information; echo command is used to output strings, so that the output information of the script can be read more easily. The above configuration includes three commands: cd /boot /, pwd, ls -lh vml *. After executing this script file, the output result is the same as executing these three commands separately, thus realizing the automatic process of "batch processing".

Execute the script through ". / aaa.sh". Before execution, you must authorize the X permission of the file.

[root@centos01 ~]# . / AAA. Sh <! -- run script file -- >
/boot
-rwxr-xr-x. 1 root root 5.7M 10 Month 2322:35 vmlinuz-0-rescue-2b580d1a2e8348b8aa9f78be11137b41
-rwxr-xr-x. 1 root root 5.7M 8 Month 232017 vmlinuz-3.10.0-693.el7.x86_64
[root@centos01 ~]# Source AAA. Sh <! -- script interpretation through source -- >
[root@centos01 ~]# SH AAA. Sh <! -- explain the script through / bin/sh -- >

Redirection and pipeline operation

1. Redirect output

Indicates to save the normal output result of the command to the specified file and overwrite the original content in the file. If the file does not exist, a new file will be created using the ">" operation symbol.

Indicates that the normal output of the command is appended to the specified file using the ">" action symbol.

for instance:

[root@centos01 ~]# Echo "AAA" <! -- data output to display -- >
aaa
[root@centos01 ~]# Echo "AAA" > 1. TXT <! -- output data to file -- >
[root@centos01 ~]# Cat 1.txt <! -- view data in file -- >
aaa
[root@centos01 ~]# Echo "BBB" >
[root@centos01 ~]# Cat 1.txt <! -- view file -- >
aaa
bbb

2. Redirect input

Redirecting input refers to changing the way to receive input from the command from the defau lt keyboard to the specified file, rather than waiting for input from the keyboard. Redirection input uses the '<' operator.

for instance:
When using the passwd command to set the password for the user, you must input the password string twice according to the prompt each time, which is very tedious. If you use the redirection input instead, you can omit the interactive process and complete the password setting automatically.

[root @ centos01 ~] (useradd bob <! -- create bob user -- >
[root @ centos01 ~] (VIM password. TXT <! -- add initial password string -- >
PWD @ 123 <! -- the password is PWD @ 123 -- >
[root @ centos01 ~] (passwd -- stdin Bob < password. TXT <! -- take the password from the password.txt file -- >
Change the password for user bob.
passwd: all authentication tokens have been successfully updated.

3. Error redirection

Error redirection refers to saving the error information (such as option or parameter error) during command execution to the specified file instead of directly displaying on the screen. Error redirection uses the "2 >" operator, where "2" refers to the number of the error file (when using standard output and standard input redirection, the 1 and 0 numbers are actually omitted).

for instance:
Do the following to save the error messages that appear when using the tar command for backup to the 3.txt file.

[root@centos01 ~]# tar jcf /nonedir/etc.tgz /etc/ 2> 3.txt
[root@centos01 ~]# 
[root@centos01 ~]# cat 3.txt
tar: Remove the leading from the member name“/"
tar (child): /nonedir/etc.tgz: Unable open: There is no file or directory
tar (child): Error is not recoverable: exiting now

When using the "2 >" operator, the content of the target file will be overwritten as if using the ">" operator. If you want to append content instead of overwriting the file, you should use the "2 >" operator instead.
When the output result of the command may include both standard output (normal execution) information and error output information, you can use the operator ">" "2 >" to save the two types of output information to different files, or you can use the "& >" operator to save the two types of output information to the same file.
for instance:

[root@centos01 ~]# VIM httpd.sh <! -- new httpd.sh file -- >
#!/bin/bash
#Automatic compilation and installation of httpd server
cd /usr/src/httpd-2.2.17/
echo "1.To configure Apache Services:"
./configure --prefix=/usr/local/httpd --enable-so --enable-rewrite --enable-charset-lite --enable-cgi &> /dev/null
echo "2.Compile Apache Services:"
make &> /dev/null
echo "3.install Apache Services:"
make install &> /dev/null
[root@centos01 ~]# Chmod + X httpd. Sh <! -- add x permission -- >
[root@centos01 ~]# . / httpd. Sh <! -- run script file -- >
1.To configure Apache Services:
2.Compile Apache Services:
3.install Apache Services:

4. Pipeline operation

Pipe operation provides a mechanism for collaborative work between different commands. The output of the command on the left side of the pipe symbol "|" will be the input (processing object) of the command on the right side. Multiple pipes can be used in the same command line.

for instance:

[root@centos01 ~]# Grep "/ bin / bash $" / etc / passwd <! -- before extraction -- >
root:x:0:0:root:/root:/bin/bash
test:x:1000:1000:test:/home/test:/bin/bash
bob:x:1002:1002::/home/bob:/bin/bash
[root@centos01 ~]# Grep "/ bin / bash $" / etc / passwd| awk - F: '{print $1, $7}' <! -- after extraction -- >
root /bin/bash
test /bin/bash
bob /bin/bash
[root@centos01 ~]# DF - HT <! -- before extraction -- >
//Filesystem type capacity used% free used mount point
/dev/sda3      xfs        76G  5.2G   71G    7% /
devtmpfs       devtmpfs  474M     0  474M    0% /dev
tmpfs          tmpfs     489M     0  489M    0% /dev/shm
tmpfs          tmpfs     489M  6.9M  482M    2% /run
tmpfs          tmpfs     489M     0  489M    0% /sys/fs/cgroup
/dev/sda1      xfs       197M  136M   61M   70% /boot
tmpfs          tmpfs      98M     0   98M    0% /run/user/0
/dev/sr0       iso9660   664M  664M     0  100% /mnt
[root@centos01 ~]# DF - HT | grep "/ $" | awk '{print $6}' <! -- after extraction, grep "/ $" means extracting the line ending with "/ -- >
7%

The role of the awk command in the above is to output the first and seventh region strings separated by a colon ':'. The "- F" part is used to specify the division symbol (if not specified, it is separated by spaces or tabs by default).

3. Use Shell variable

The concept of "variable" is used in various shell environments. Shell variables are used to store specific parameters (values) that the system and users need to use, and these parameters can be changed according to user settings or system environment changes. By using variables, shell programs can provide more flexible functions and more adaptability.
Common Shell variable types include custom variable, environment variable, location variable and predefined variable.

1. Custom variable

Custom variable is a variable defined by the system user, which is only valid in the user's own Shell environment, so it is also called local variable. When writing Shell script programs, some specific custom variables are usually set to adapt to various changes in the process of program execution and meet different needs.

1) define new variables

The basic format of defining variables is "variable name = variable value", and there is no space between equal signs. The variable name should start with a letter or underscore, and the name should not contain special characters (such as +, -, *, /? ,%, &, ා, etc.).

[root@centos01 ~]# li=python
[root@centos01 ~]# version=2.7.13

2) view and reference the value of variables

You can reference the value of a variable by adding the leading symbol "$" before the variable name. You can use the echo command to view variables, and you can view multiple variable values in one echo command at the same time.

[root@centos01 ~]# echo $li
python
[root@centos01 ~]# echo $version
2.7.13
[root@centos01 ~]# echo $li $version
python 2.7.13

3) special operation of variable assignment

Directly specifying the variable content after the equal sign "=" is the most basic method for variable assignment. In addition, there are some special assignment operations, which can be more flexible for variable assignment, so as to be applicable to various complex management tasks.

(1) double quotation marks ("")

[root@centos01 ~]# Python = Python 2.7.13 <! -- wrong assignment -- >
bash: 2.7.13: Command not found...
[root@centos01 ~]# Python = "Python 2.7.13" <! -- correct assignment -- >
[root@centos01 ~]# Echo $Python <! -- view value -- >
python 2.7.13

Within double quotation marks, the "$" symbol can be used to refer to the value of other variables (variable reference), so that the value of existing variables can be directly called to assign to new variables.

[root@centos01 ~]# echo $version
2.7.13
[root@centos01 ~]# sqlserver="sqlserver $version" 
                                       <!--Assign values to variables-->
[root@centos01 ~]# Echo $sqlserver <! -- view value -- >
sqlserver 2.7.13

(2) single quotation mark (')

Single quotation marks should be used when the content to be assigned contains characters with special meanings such as $, "", \. In the range of single quotation marks, the values of other variables cannot be referenced, and any characters are treated as normal characters.

[root@centos01 ~]# Sqlserver = $sqlserver version '<! -- $symbol can no longer reference variable -- >
[root@centos01 ~]# Echo $sqlserver <! -- output string as is -- >
sqlserver $version

③ apostrophe (`)

The apostrophe is mainly used for command replacement, which allows the screen output of a command to be assigned to a variable. The range enclosed by the apostrophe must be the command line that can be executed, otherwise an error will occur.

[root@centos01 ~]# ls -lh `which useradd`
-rwxr-x---. 1 root root 116K 11 Month 62016 /usr/sbin/useradd

The above operation is equivalent to executing two consecutive commands: first, find out the program location of the useradd command through which useradd command, and then list the file properties according to the search results. During execution, the entire range of apostrophes is replaced with the output of the which useradd command.

④ read command

In addition to the above assignment, you can use bash's built-in command read to assign values to variables. The read command is used to prompt the user to enter information, so as to realize a simple interaction process. During execution, a line of content will be read in from the standard input device (keyboard), and each field read in will be assigned to the specified variable (redundant content will be assigned to the last variable) in turn with the space as the separator. If only one variable is specified, the entire line is assigned to this variable.

[root @ centos01 ~] (read - P "enter the required content:" insert
 Input the required content: Hello <! -- Hello! Assign to variable insert -- >
[root@centos01 ~]# echo $insert
 Hello!

4) set the action range of variables

By default, the newly defined variables are only valid in the current Shell environment, so they are called local variables. When entering a subprogram or a new subshell environment, local variables are no longer available. For example, when Bash is executed directly to enter a new subshell script, variables such as li and version defined in the parent Shell environment cannot be referenced.

[root@centos01 ~]# Echo "$Li $version" <! -- view currently defined variable values -- >
python 2.7.13
[root@centos01 ~]# Bash <! -- enter the sub shell environment -- >
[root@centos01 ~]# Echo "$Li $version" <! -- cannot call variables in the parent shell environment -- >
[root@centos01 ~]# Exit <! -- return to the original shell environment -- >
exit
[root@centos01 ~]# Echo "$Li $version" <! -- view currently defined variable values -- >
[root@centos01 ~]# Export Li version <! -- set as global variable -- >
[root@centos01 ~]# Bash <! -- enter the sub shell environment -- >
[root@centos01 ~]# Echo "$Li $version" <! -- global variables of the parent shell can be called -- >
python 2.7.13
[root@centos01 ~]# Exit <! -- return to the original shell environment -- >
exit

5) operation of numerical variables

Shell variable's numerical operation is mostly used in the process control of script program (such as cycle times, usage comparison, etc.) and then in Bash shell environment, only simple certificate operation can be carried out, and decimal operation is not supported. The operation of integer value is mainly carried out by internal command expr, and the basic format is as follows:

expr variable 1 operator variable 2 [operator variable 3]

Among them, variable 1, variable 2... Correspond to the numerical variable to be calculated (it needs to be called with "$"), and the commonly used operators are as follows:
+: addition operation;
-: subtraction;
*: multiplication operation; note that "*" symbol cannot be used only, otherwise it will be regarded as a file wildcard;
/: division operation;
%The modular operation, also known as the remainder operation, is used to calculate the remainder after the value is divided;

for instance:

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

2. Special shell variables

1) environment variables:

Use the command "env" to view the environment variables in the current working environment. The value of environment variable is automatically maintained by Linux system and will change with the change of user status.
The PATH variable is used to set the default search PATH of the executable program. For example, add the root directory to the default search PATH: PATH = $PATH: / root. If it is not found, it will prompt "command not found"

The global configuration file for environment variables is / etc/profile, in which the variables defined act on all users.

No user independent configuration is found at ~ /. bash_profile

After modifying the variable file, you must use the source command to re read the load or restart to take effect.

2) position variable:

Position variable is also called position parameter. In the command "ls -lh /boot", the position variable of ls is $0, the position variable of - LH is $1, and the position variable of / boot is $2. and so on.

3) predefined variables:

Predefined variable is a kind of special variable pre-defined by bash program. Users can only use predefined variables, but can not create new predefined variables, nor directly assign values to predefined variables. Predefined variables are represented by a combination of "$" and another symbol. The meanings of several predefined variables are as follows:

  • $#: indicates the number of location parameters in the command line.

  • $*: indicates the contents of all location parameters.

  • $?: indicates the status returned after the execution of the previous command. A return of 0 indicates correct execution. A return of any value other than 0 indicates an exception.

  • $0: indicates the name of the currently executing script or program.

——————Thank you for reading——————

Tags: Linux shell Python Apache vim

Posted on Mon, 04 Nov 2019 19:50:47 -0500 by adammo