Shell scripting basics and redirection and pipeline operations

A, Shell Script basics

Shell scripts Linux system is a special application, it ranged between kernel and user operating system, acted as a "command interpreter" is responsible for receiving operation commands entered by the user and interpreted, you will need to perform passed to the kernel operations performed, and outputs the result.

1, a simple preparation of Shell scripts

[root@01 ~]# vim aaa.sh    <!--新建aaa.sh文件-->
#!/bin/bash
#Description E-Mail:[email protected] BY:LYX
cd /boot/
echo "显示当前目录:"
pwd
echo "查看以vml开头的文件:"
ls -lh vml*
[root@centos01 ~]# chmod +x aaa.sh     <!--添加可执行权限-->

Above aaa.sh script file, the first line "! # / Bin / bash" is a line of special script declaration that after this line statement to explain the implementation by / bin / bash program; the other with "#" at the beginning of the sentence represents annotation information; echo command output string, so that the output information is easier to read the script. The above-described configuration includes three commands: cd / boot /, pwd, ls -lh vml *. After executing this script file, and output the results in order to perform the three separate commands are the same, in order to achieve a "batch" process automation.

Execute the script by "./aaa.sh" way, you must be authorized in the X authority file prior to execution.

[root@centos01 ~]# ./aaa.sh    <!--运行脚本文件-->
/boot
-rwxr-xr-x. 1 root root 5.7M 10月 23 22:35 vmlinuz-0-rescue-2b580d1a2e8348b8aa9f78be11137b41
-rwxr-xr-x. 1 root root 5.7M 8月  23 2017 vmlinuz-3.10.0-693.el7.x86_64
[root@centos01 ~]# source aaa.sh  <!--通过source来解释脚本-->
[root@centos01 ~]# sh aaa.sh     <!--通过/bin/sh来解释脚本-->

Second, the operation of the pipeline and redirect

1, redirect output

Shows a normal save command output to a specified file, overwriting the original content file, if the file does not exist, a new file with a ">" sign operation.

Shows a normal output command appended to the specified file using sh ">>" operation symbols.

for example:

[root@centos01 ~]# echo "aaa"  <!--数据输出到显示器上显示-->
aaa
[root@centos01 ~]# echo "aaa" > 1.txt    <!--将数据输出到文件中-->
[root@centos01 ~]# cat 1.txt      <!--查看文件中数据-->
aaa
[root@centos01 ~]# echo "bbb" >> 1.txt      <!--将数据追加输出到1.txt文件中-->
[root@centos01 ~]# cat 1.txt         <!--查看文件-->
aaa
bbb

2, redirect input

Redirect input refers to the way in order to receive input from the keyboard instead of the default specified file, instead of waiting for input from the keyboard. Redirection inputs "<" operator.

For example:
Use the passwd command the user to set a password every time a password must be entered twice prompted string, very cumbersome, if the input redirection switch of the interactive process can be omitted, and automatically setting the password.

[root@centos01 ~]# useradd bob  <!--创建bob用户-->
[root@centos01 ~]# vim password.txt     <!--添加初始密码串-->
pwd@123                    <!--密码为pwd@123-->
[root@centos01 ~]# passwd --stdin bob < password.txt      <!--从password.txt文件中取密码-->
更改用户 bob 的密码 。
passwd:所有的身份验证令牌已经成功更新。

3, error redirection

Error redirection refers to the implementation of the error message (such as options or parameter error, etc.) is saved to the specified file, rather than displayed directly on the screen command procedures arise. Error redirection "2>" operator, where "2" refers to the number of error file (when using the standard output and standard input redirection, 1,0 number actually omitted).

For example:
Do the following error message may occur when using the tar command to save the backup to 3.txt file.

[root@centos01 ~]# tar jcf /nonedir/etc.tgz /etc/ 2> 3.txt
[root@centos01 ~]# 
[root@centos01 ~]# cat 3.txt
tar: 从成员名中删除开头的“/”
tar (child): /nonedir/etc.tgz:无法 open: 没有那个文件或目录
tar (child): Error is not recoverable: exiting now

"2>" when the operator would be like using the ">" operator as to cover the contents of the target file, to the additional content rather than overwriting the file, you should use "2 >>" operator.
When the result of the command output i.e. may include standard output (normal execution) information, and output information includes an error, the operator can use the ">" "2>" are the two types of output information saved to different files, may be used. " &> "operator to save two types of output information to the same file.
for example:

[root@centos01 ~]# vim httpd.sh   <!--新建httpd.sh文件-->
#!/bin/bash
#自动编译安装httpd服务器
cd /usr/src/httpd-2.2.17/
echo "1.配置Apache服务:"
./configure --prefix=/usr/local/httpd --enable-so --enable-rewrite --enable-charset-lite --enable-cgi &> /dev/null
echo "2.编译Apache服务:"
make &> /dev/null
echo "3.安装Apache服务:"
make install &> /dev/null
[root@centos01 ~]# chmod +x httpd.sh   <!--添加X权限-->
[root@centos01 ~]# ./httpd.sh     <!--运行脚本文件-->
1.配置Apache服务:
2.编译Apache服务:
3.安装Apache服务:

4, the pipeline operation

Conduit (pipe) operation provides a mechanism for collaborative work between the different commands, located conduit "|" symbol on the left side of the output result of the command, the (processed), in the same row as the right of the input command may be a command the use of multiple pipes.

for example:

[root@centos01 ~]# grep "/bin/bash$" /etc/passwd  <!--提取前-->
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}'   <!--提取后-->
root /bin/bash
test /bin/bash
bob /bin/bash
[root@centos01 ~]# df -hT     <!--提取之前-->
文件系统       类型      容量  已用  可用 已用% 挂载点
/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}'   <!--提取之后其中grep “/$”表示提取以“/”结尾的行-->
7%

The action of the command is awk colon ":" as the separator, a first output, a string of seven regions. Wherein "-F" section specifies segmentation symbols (where not specified, the default separated by spaces or tabs).

Third, the use 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 using variables, Shell program to provide more flexible functionality, and adaptable.
Shell variables common types include custom variables, environment variables, location variables, predefined variables.

1, custom variables

Custom variables are variables defined by the user's own system, only available in the user's own Shell environment, so-called local variables. When writing Shell scripts, usually set some specific custom variables to adapt to changes during program execution, to meet different needs.

1) Define a new variable

The basic format is defined as the variable "variable variable name = value", equal on both sides with no spaces. Variable names need to start with a letter or an underscore, names do not contain special characters (such as +, -?, *, /,%, &, #, Etc.).

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

2) View and reference variable values

By adding a preamble symbol before the variable name "$", you can reference the value of a variable. Use the echo command to view the variables, you can simultaneously view multiple variable values ​​in an echo command.

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

3) special operations variable assignment

In the equal sign "=" directly behind the specified variable content is the most basic method for the variable assignment, in addition, there are some special assignment, it can be more flexible position variable assignment, in order for a variety of complex administrative tasks.

① double quotation marks ( "")

[root@centos01 ~]# PYTHON=python 2.7.13  <!--错误赋值-->
bash: 2.7.13: 未找到命令...
[root@centos01 ~]# PYTHON="python 2.7.13" <!--正确的赋值-->
[root@centos01 ~]# echo $PYTHON   <!--查看值-->
python 2.7.13

In double quotes range, using the "$" symbol can reference the value of other variables (reference variable), it is possible to directly call the existing values ​​assigned to the new variable.

[root@centos01 ~]# echo $version
2.7.13
[root@centos01 ~]# sqlserver="sqlserver $version" 
                                       <!--以变量的值进行赋值-->
[root@centos01 ~]# echo $sqlserver    <!--查看值-->
sqlserver 2.7.13

② single quotation marks ( '')

When the content to be assigned contains $, ", \ and other characters that have special meaning, you should use single quotes in single quotes range, will not reference values ​​of other variables, any characters are treated as ordinary characters.

[root@centos01 ~]# sqlserver='sqlserver $version'  <!--$符号不能再引用变量-->
[root@centos01 ~]# echo $sqlserver      <!--原样输出字符串-->
sqlserver $version

③ anti apostrophe ( `)

Anti apostrophe is mainly used in command substitution, variable screen allows you to perform the output of a command assigned to. Command enclosed anti-apostrophe must be able to perform a range of rows, otherwise it will go wrong.

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

Corresponds to the above-described operation performed continuously two commands - to find out the position of the program by Which useradd command useradd command, then the file attributes in accordance with the search result. During execution, the apostrophe will replace the entire range of anti output result which useradd command.

④read command

In addition to the above assignment can also be used to read bash built-in commands to assign values ​​to variables. read command is used to prompt the user to enter information, enabling simple interaction. When executed from standard input device (keyboard) reads a single line, and as a space separator, the fields will be read sequentially assigned to the specified variable (redundant elements assigned to the last variable). If only a specified variable, the entire line will be assigned to this variable.

[root@centos01 ~]# read -p "输入需要的内容:" insert
输入需要的内容:您好!  <!--将您好!赋值给变量insert-->
[root@centos01 ~]# echo $insert
您好!

Scope 4) disposed variables

By default, a new variable is valid only in the defined current Shell environment, so called local variables. When entering new subroutine or sub-Shell environment, local variables will no longer be available. For example, direct execution after a new child into the Bash Shell script, you can not quote li, version Shell environment variables such as parent defined.

[root@centos01 ~]# echo "$li $version"   <!--查看当前定义的变量值-->
python 2.7.13
[root@centos01 ~]# bash            <!--进入子shell环境-->
[root@centos01 ~]# echo "$li $version"        <!--无法调用父shell环境中的变量-->
[root@centos01 ~]# exit        <!--返回原有的shell环境-->
exit
[root@centos01 ~]# echo "$li $version"   <!--查看当前定义的变量值-->
[root@centos01 ~]# export li version     <!--设置为全局变量-->
[root@centos01 ~]# bash          <!--进入子shell环境-->
[root@centos01 ~]# echo "$li $version" <!--可以调用父shell的全局变量-->
python 2.7.13
[root@centos01 ~]# exit     <!--返回原有的shell环境-->
exit

5) calculating the value of variable

Shell value calculation process variables used for the control script program (e.g., cycle number, amount, etc. Comparative) then Bash shell environment, only a simple operation certificate does not support fractional arithmetic. Integer calculation performed primarily by internal command expr, the basic format is as follows:

expr 变量1 运算符 变量2 [运算符 变量3]...

Wherein, the variables 1, 2 ...... variable corresponding to values of the variables (requires a "$" symbol to call) to be calculated, several operators are used the
+: adder;
-: subtraction;
* : multiplication; Note that not only the "*" symbol, as would otherwise be the file masks;
/: division;
%: modulo operation, also called modulo arithmetic, the value of the remainder for the division calculation;

for example:

[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" can view the environment variables in the current working environment. Value of the environment variables are automatically maintained by the Linux system, users will change with the state of change.
Where the default search path PATH variable used to set the executable program, such as adding to the root directory of the default search path: PATH = "$ PATH: / root" If you can not find you will be prompted to "command not found"

Environment variables global configuration file: / etc / profile, variables defined in this document apply to all users.

Located no user standalone configuration: ~ / .bash_profile

After modifying variable file must use the source command to reread the load or restart to take effect.

2) variable positions:

Position variable, also known as positional parameters in the command "ls -lh / boot", the position variable ls is $ 0, -lh position variables $ 1, / location variable boot is $ 2. And so on.

3) predefined variables:

Predefined variables are pre-defined by the program good bash a special class of variables, users can only use predefined variables, but can not create a new predefined variables can not be directly assigned to predefined variables. Predefined variables using the "$" symbol and another symbol represents a combination of several predefined variables often following meanings:

  • $ #: Indicates the number of command line positional parameters.

  • $ *: Indicates that everything positional parameters.

  • Previous command $ ?: represents the execution state after the return, returns 0 executed correctly, return any value other than 0 indicates abnormal execution.

  • $ 0: represents the name of a script or program currently being executed.

Guess you like

Origin www.linuxidc.com/Linux/2019-11/161413.htm
Recommended