shell scripts notes (linux script)

Foreword

If you want to select operation and maintenance, or have a certain interest in the linux system, I think we must know how shell scripts, because this thing really well; why? ? That is because:
1, an important basis for automated management of
2, tracking and management system, an important work of
3, simple intrusion detection function
4, a single continuous instruction of
5, simple data processing (most based on regular expression processing)
6, cross-platform support and a shorter learning process (Unix Like almost all of the above can run shell script, even MS Windows series also related to the script emulator can be used)

Writing your first shell

In writing the shell script also need to use the following precautions:

  1. Instruction is executed from the top down, left-to-right analysis and execution;
  2. Issued instructions just as referred to in Chapter 4: multiple blank will be among the command options and arguments to be ignored;
  3. Blank lines will also be ignored, and [Tab] key is pushed the blank key blank likewise considered;
  4. If the read-Enter a symbol (CR), to try to begin execution of the row (or the string) command;
  5. As if the contents of a line too, you can use "[Enter]" to extend to the next line;
  6. "#" Can be used as comment! Any increase in the back of the # data will be treated as comment text to be ignored!

How to perform shell file? By about in several ways:
the direct command is given: shell.sh file must have the permission to read and execute (RX) is then:
1, absolute path: /home/dmtsai/shell.sh used to give instructions;
2, relative path: Suppose working directory / home / dmtsai /, is used to perform ./shell.sh
3, the variable "pATH" function: pATH shell.sh placed in the specified directory, for example: ~ / bin /
to bash program to perform: to perform through "bash shell.sh" or "sh shell.sh"

第一个shell例子:
[dmtsai@study ~]$ mkdir bin; cd bin
[dmtsai@study bin]$ vim hello.sh
#!/bin/bash
#Program:
#This program shows “Hello World!” in your screen.
#History:
#2015/07/16 VBird First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo -e “Hello World! \a \n”
exit 0

1. The first line # / bin / bash in declaring the name of the shell script used:!
Because we are using bash, so, must be based on " ! # / Bin / bash " to declare the use of grammar in this document to bash grammar! Then when the program is executed, he will be able to load the relevant environmental bash configuration files (generally is non-login shell of ~ / .bashrc), and execute bash allows us to be able to perform the following instructions! This is very important!

2. Description of program content:
the entire script them, "! #" In addition to the first line is used to declare outside the shell, the other # are "notes" use! Therefore, among the above procedure, the following second row is used to explain the basic data of the entire program. In general, it is recommended that you must develop the script's description:

  1. Content and functionality;
  2. Version Information;
  3. Author and contact details;
  4. Creation date;
  5. History and so on. This will help rewrite the future program and debug it!

3. declared major environmental variables:
recommended To be sure some important environment variable is set, PATH and LANG (if you are using the output related information) is among the most important! In this way, you can let us during this program, some external commands can be issued directly, without having to write the absolute path it! More convenient it!

4. The main part of the program
will be written to the main program! In this example, which is the echo that line it!

5. inform the implementation of the outcome (defined return value)
of an instruction execution success or not, you can use the $? Variable to observe - then we can also use this command to exit the program to interrupt, and return a value to the system. Use exit 0 In this example, among which represents a departure script and return 0 to the system.

Further, it may also be used: " the chmod + A or X hello.sh ./hello.sh " Script performs this!

Be sure to develop good habits script writing, at the beginning of a good record in each script file:
script function;
script version information;
script author and contact information;
copyright script declaration of way;
History (history) of the script ;
more specific instructions in the script, using the "absolute path" approach to issued;
required environment variables declared in advance and set script is running.

Simple example:
in order to use read instructions, write a script, he can let the user enter: 1. first name and 2. last name, and finally displayed on the screen: "Your full name is:" Content:
[dmtsai bin @study] $ vim showname.sh
! # / bin / bash
#Program:
#User the Inputs His-First name and Last name Full Program Shows His-name..
#history:
# 2015/07/16 VBird First Release
the PATH = / bin : / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
Export the PATH
the Read -p "Please the iNPUT your First name:" prompt the user to enter FirstName #
read -p "Please input your last name :" lastname # prompting the user to input
echo -e "\ nYour full name is : $ {firstname} $ {lastname}" # result output by the screen

With the date change: the use of date created files
[dmtsai @ Study bin] $ vim create_3_filename.sh
# / bin / bash!
#Program:
#Program Creates Three Files, Which named by the User's date the INPUT and the Command.
#History:
# 2015 / 07/16 VBird First Release
the PATH = / bin: / sbin: / usr / bin: / usr / sbin: / usr / local / bin: / usr / local / sbin: ~ / bin
Export the PATH
# 1 lets users. enter the file name, and made fileuser this variable;
echo -e. "by Will use the I 'Touch' to the Create the Command files 3" # pure display information
read -p "Please input your filename: " fileuser # prompt the user to input
# 2. In order to avoid arbitrary user press Enter, the use of variable functional analysis of the file name if there is set?
= filename Katex the parse error: the Expected 'the EOF', GOT '#' AT position 24: R & lt ...: - "filename"} # Start determine whether a configuration file name. 3 ... # (DATE --date = '2 Days ago Member' +% Y% m% d) # date two days before
date2 = $ (date --date = ' 1 days ago' +% Y% m% d) # previous day
date3 = $ (date +% Y % m% d) # today's date
file1 = f i l e n a m e {filename} {#} date1 following three lines in the configuration file name
file2 = f i l e n a m e {filename} {date2}
file3= f i l e n a m e {filename} {} date3
#. 4. The file name created it!
Touch "Katex the parse error: the Expected 'EOF', GOT '#' position AT 10: {file1}" # The following three lines in the file creation ... touc{file2} "
Touch" $ {file3} "

数值运算:简单的加减乘除
[dmtsai@study bin]$ vim multiplying.sh
#!/bin/bash
#Program:
#User inputs 2 integer numbers; program will cross these two numbers.
#History:
#2015/07/16 VBird First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo -e “You SHOULD input 2 numbers, I will multiplying them! \n”
read -p "first number: " firstnu
read -p "second number: " secnu
total=$ (( f i r s t n u {firstnu}* {secnu} ))
echo -e “\nThe result of ${firstnu} x ${secnu} is ==> ${total}”

数值运算:通过 bc 计算 pi
[dmtsai@study bin]$ vim cal_pi.sh
#!/bin/bash
#Program:
#User input a scale number to calculate pi number.
#History:
#2015/07/16 VBird First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo -e “This program will calculate pi value. \n”
echo -e “You should input a float number to calculate pi value.\n”
read -p "The scale number ( 10~10000 ) ? " checking
num=KaTeX parse error: Expected 'EOF', got '#' at position 18: …hecking:-"10"} #̲ 开始判断有否有输入数值 ec…{num}; 4*a ( 1 ) " | bc -lq

Implementation of the differences shell script (source, sh script, ./script)

When the script is executed, the use of such implementation using the direct execution, in fact, script is executed within the subroutine bash! When the subroutine is completed, the variable or operation within the subprogram will end without back to the parent program

Using source to execute the script: execute in the parent program

Determined using the formula

Using a test instruction test function
Here Insert Picture Description
Here Insert Picture Description

Judgment and let the user enter a file name, we judge:

  1. If the file exists, if there is given a "Filename does not exist" message, and the interrupt routine;
  2. If this file exists, it is determined that he is a file or directory, the resulting output "Filename is regular file" or "Filename is directory"
  3. Determine what, executive privilege identity of the file or directory is owned by, and data output permission!
    After executing this script, he will be checked in accordance with the file name you entered Oh! Look at whether or not there, look for the file or directory type, final judgment authority.

[dmtsai@study bin]$ vim file_perm.sh
#!/bin/bash
#Program:
#User input a filename, program will check the flowing:
#1. ) exist? 2. ) file/directory? 3. ) file permissions
#History:
#2015/07/16 VBird First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
#1. 让使用者输入文件名,并且判断使用者是否真的有输入字串?
echo -e “Please input a filename, I will check the filename’s type and permission. \n\n”
read -p “Input a filename : " filename
test -z ${filename} && echo “You MUST input a filename.” && exit 0
#2. 判断文件是否存在?若不存在则显示讯息并结束脚本
test ! -e KaTeX parse error: Expected 'EOF', got '&' at position 12: {filename} &̲& echo "The fil…{filename}’ DO NOT exist” && exit 0
#3. 开始判断文件类型与属性
test -f ${filename} && filetype=“regulare file”
test -d ${filename} && filetype=“directory”
test -r ${filename} && perm=“readable”
test -w KaTeX parse error: Expected 'EOF', got '&' at position 12: {filename} &̲& perm="{perm} writable"
test -x KaTeX parse error: Expected 'EOF', got '&' at position 12: {filename} &̲& perm="{perm} executable"
#4. 开始输出信息!
echo “The filename: ${filename} is a ${filetype}”
echo “And the permissions for you are : ${perm}”

利用判断符号 [ ]

如果要知道 H O M E [ d m t s a i @ s t u d y   ] {HOME} 这个变量是否为空的,可以这样做: [dmtsai@study ~] [ -z “${HOME}” ] ; echo $?

如果要在 bash 的语法当中使用中括号作为 shell 的判断式时,必须要注意中括号的两端需要有空白字符来分隔喔! 假设我空白键使用 “□” 符号来表示,那么,在这些地方你都需要有
空白键:
[ “ H O M E " = = " HOME" == " MAIL” ]
[□" H O M E " = = " HOME"□==□" MAIL"□]
↑ ↑ ↑ ↑

使用中括号的判断来做一个小案例好了,案例设置如下:

  1. 当执行一个程序的时候,这个程序会让使用者选择 Y 或 N ,
  2. 如果使用者输入 Y 或 y 时,就显示 “ OK, continue ”
  3. 如果使用者输入 n 或 N 时,就显示 “ Oh, interrupt ! ”

如果不是 Y/y/N/n 之内的其他字符,就显示 “ I don’t know what your choice is ”
利用中括号、 && 与 || 来继续吧!
[dmtsai@study bin]$ vim ans_yn.sh
#!/bin/bash
#Program:
#This program shows the user’s choice
#History:
#2015/07/16 VBird First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
read -p "Please input ( Y/N ) : " yn
[ “ y n " = = " Y " o " {yn}" == "Y" -o " {yn}” == “y” ] && echo “OK, continue” && exit 0
[ “ y n " = = " N " o " {yn}" == "N" -o " {yn}” == “n” ] && echo “Oh, interrupt!” && exit 0
echo “I don’t know what your choice is” && exit 0

shell script 的默认变量( $0, $1… )

如果通过指令后面接参数, 那么一个指令就能够处理完毕而
不需要手动再次输入一些变量行为!这样下达指令会比较简单方便啦!
script 是怎么达成这个功能的呢?其实 script 针对参数已经有设置好一些变量名称了!对应如下:
/path/to/scriptname opt1 opt2 opt3 opt4
$0 $1 $2 $3 $4
执行的脚本文件名为 $0 这个变量,第一个接的参数就是 $1 啊~ 所以,只要我们在 script 里面善用 $1 的话,就可以很简单的立即下达某些指令功能了!除了这些数字的变量之外, 我们还有一些较为特殊的变量可以在 script 内使用来调用这些参数!
$# :代表后接的参数 “ 个数 ” ,以上表为例这里显示为 “ 4 ” ;
$@ :代表 “ “$1” “$2” “$3” “$4” ” 之意,每个变量是独立的(用双引号括起来);
$* :代表 “ “$1c$2c$3c$4” ” ,其中 c 为分隔字符,默认为空白键, 所以本例中代表 “ “$1 $2 $3 $4” ” 之意。

执行一个可以携带参数的 script ,执行该脚本后屏幕会显示如下的数据:
程序的文件名为何?
共有几个参数?
若参数的个数小于 2 则告知使用者参数数量太少
全部的参数内容为何?
第一个参数为何?
第二个参数为何?

[dmtsai@study bin]$ vim how_paras.sh
#!/bin/bash
#Program:
#Program shows the script name, parameters…
#History:
#2015/07/16 VBird First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo “The script name is ==> ${0}”
echo “Total parameter number is ==> KaTeX parse error: Expected 'EOF', got '#' at position 1: #̲" [ "#” -lt 2 ] && echo “The number of parameter is less than 2. Stop here.” && exit 0
echo “Your whole parameter is ==> ‘$@’”
echo “The 1st parameter ==> ${1}”
echo “The 2nd parameter ==> ${2}”

执行结果如下:
[dmtsai@study bin]$ sh how_paras.sh theone haha quot
The script name is ==> how_paras.sh <==文件名
Total parameter number is ==> 3 <==果然有三个参数
Your whole parameter is ==> ‘theone haha quot’ <==参数的内容全部
The 1st parameter ==> theone <==第一个参数
The 2nd parameter ==> haha <==第二个参数

shift :造成参数变量号码偏移

我们将 how_paras.sh 的内容稍作变化一下,用来显示每次偏移后参数的变化情况:
[dmtsai@study bin]$ vim shift_paras.sh
#!/bin/bash
#Program:
#Program shows the effect of shift function.
#History:
#2009/02/17 VBird First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo “Total parameter number is ==> KaTeX parse error: Expected 'EOF', got '#' at position 1: #̲" echo "Your wh…@’”
shift # 进行第一次“一个变量的 shift ”
echo “Total parameter number is ==> KaTeX parse error: Expected 'EOF', got '#' at position 1: #̲" echo "Your wh…@’”
shift 3 # 进行第二次“三个变量的 shift ”
echo “Total parameter number is ==> KaTeX parse error: Expected 'EOF', got '#' at position 1: #̲" echo "Your wh…@’”

Execution results are as follows:
[dmtsai @ Study bin] $ SH shift_paras.sh at Four Five Six Three One TWO <== given six parameters
Total parameter number is ==> 6 < == most primitive parameter variable circumstances
Your whole parameter is = => 'one TWO Three Four Five Six'
the Total Number Parameter IS ==>. 5 <== first shift, the first one found the following to see missing
Your whole parameter is ==> 'two three four five six'
Total parameter number is ==> 2 < == second offset out three, two three four missing
Your whole parameter is ==> 'five six'

Epilogue

The use of these basic operations are shell, followed by an article will use the terms under which these statements.

Published 19 original articles · won praise 0 · Views 1399

Guess you like

Origin blog.csdn.net/qq_22356995/article/details/104209650