linux Started Series 8 - shell programming entry

This will combine the Linux command described earlier, pipeline breaks and other knowledge, the preparation of Shell scripts VI editor, can achieve automation script file.

As mentioned in explain commonly used Linux command "linux entry will be new to the series 5-- linux command," a text, Shell terminal interpreter is a bridge human-computer interaction, is the translator between the user and the kernel. As intermediary in communication with an internal user Linux system, to provide users with a Linux kernel for sending a request to run the transverse interface system level program, the user can start by Shell, suspend, stop the program.

A, Shell scripting and programming Overview

1.1 Shell is not only the terminal interpreter

Shell is actually not only a command-line interpreter, in addition it can control startup programs, stop, suspend other operations, it is a powerful programming language, easy to write, easy to debug, flexibility. Shell is an interpreted scripting language, you can call Linux system commands .

Shell In addition to supporting a variety of variables and parameters, but also provides the control features such as looping, branching and other high-level programming languages ​​ago. To properly use these features, accurate orders is particularly important, before explaining specific programming syntax, first learn about the implementation Shell script.

1.2 Shell scripts work

Shell script command works in two ways: interactive and batch .

  • Interactive: Interactive, the user does not enter a command is executed immediately. So far all this way previously taken.
  • Batch: Bach, prepared in advance of a complete Shell script, the script is performed once many instructions. Next we will use is this way.

By SHELL environment variable, the terminal can view the current use system default interpreter, the interpreter defaults Bash

[root@heimatengyun ~]# echo $SHELL
/bin/bash

1.3 The first Shell Script

Shell script will be used not only learned earlier Linux commands, pipeline operators, data flow redirection rules of grammar, logic statements need to be processed through the modular internal functions should eventually form the shell script see everyday.

All programming languages ​​convention is the first program Hello World, we write a simple script with Shell

[root@heimatengyun test]# ls
test1.txt  test2.txt
[root@heimatengyun test]# echo "hello world"
hello world
[root@heimatengyun test]# vi hello.sh
#!/bin/bash
#author:heimatengyun
echo " hello world"

Save and exit. Shell script file can be any name, but in order to avoid being mistaken for ordinary files, we recommend the use of the suffix .sh, to indicate that a script file.

ps:! The first line # / bin / bash script statement is used to tell the system to execute scripts which Shell interpreter.

The second line #author: heimatengyun information is a comment on the scripting capabilities are introduced to facilitate future maintenance.

The third line echo "hello world" is the command statements, may be a simple command various linux, may be complicated by various combinations of a block of statements and logic statements grammar rules.

Shell programming format is so simple, I call Shell Programming "three-stage", after coding on the preparation to follow this format.

1.4 Shell script execution

Linux script is executed in two ways: directly executed by an interpreter, script execution via the path .

  • Direct execution by an interpreter bash

Syntax: bash or sh script name

Case: hello.sh script file before executing files created

[root@heimatengyun test]# bash hello.sh 
 hello world
[root@heimatengyun test]# sh hello.sh 
 hello world
  • Performed by the script path

Syntax: absolute or relative path to the script path

Case: hello.sh script file before executing files created

[root@heimatengyun test]# /root/test/hello.sh
-bash: /root/test/hello.sh: Permission denied
[root@heimatengyun test]# ./hello.sh
-bash: ./hello.sh: Permission denied

Nani? Lack of prompt access. Yes, you read that right, if you run a path through this way, you need to execute permissions to modify the file , (the default permissions can not be executed, and when the data path press the tab key script also does not help the whole prompt) the file permissions associated command continue to explain in a subsequent article, here to add executable permission to the script in accordance with the following commands.

[root@heimatengyun test]# ll
total 12
-rw-r--r--. 1 root root  4 Dec  1 09:48 hello.sh
[root@heimatengyun test]# chmod 777 hello.sh 
[root@heimatengyun test]# ll
total 8
-rwxrwxrwx. 1 root root 53 Dec  1 09:22 hello.sh

Performed again, this time in the input path will be prompted to press the tab key to auto-complete the

[root@heimatengyun test]# ./hello.sh 
 hello world
[root@heimatengyun test]# /root/test/hello.sh 
 hello world

Two, Shell programming syntax

After grasp Shell scripts are run, we officially entered the Shell programming syntax learning.

Any one language learning methods are not quick, can not do without a lot of practice, can only knock on more skilled in order to understand more deeply.

2.1 Variable

The Linux Shell (here is the default bash) variables into the system variables and user-defined variables, system variables including $ HOME, $ PWD, $ SHELL, $ USER, etc., user-defined variables for the user to customize according to actual needs Variables.

You can view all the variables by Shell command set.

[root@heimatengyun test]# set
BASH=/bin/bash
...省略部分内容

The main demonstration following custom variables

2.1.1 define the variable

grammar:

Variable name = value

Variable naming rules:

(1) variable names can be registered letters, numbers, and underscores, but can not start with a number

(2) on both sides of the equal sign can not have spaces

(3) General variable capital

Case:

(1) the definition of variable and

[root@heimatengyun test]# SRT="wellcome"
[root@heimatengyun test]# echo $SRT
wellcome
[root@heimatengyun test]# set |grep SRT
SRT=wellcome
[root@heimatengyun test]# env |grep SRT
[root@heimatengyun test]# 

You can see the custom variable SRT, you can check out via the set command.

(2) environment variable to a global variable

[root@heimatengyun test]# export SRT
[root@heimatengyun test]# env |grep SRT
SRT=wellcome

In the example above arguments SRT defined by the env command to view, query did not come out in the environment variables, custom variable SRT promoted to environment variables export, you can check out by env

(3) revocation of variables

[root@heimatengyun test]# unset SRT
[root@heimatengyun test]# echo $SRT

[root@heimatengyun test]# set |grep SRT
[root@heimatengyun test]# env |grep SRT

Undo command unset variables, variables will not exist after revocation

2.2 Variable assignment

In addition to direct assignment, can also be the result of command execution is assigned to variable

grammar:

`` Command = variable or variable = $ (command)

Description:

Command with backticks or $ () contains up to execute commands and then execute the command into a variable.

Case:

[root@heimatengyun test]# ls
hello.sh  test1.txt  test2.txt
[root@heimatengyun test]# RESULT=`ls`
[root@heimatengyun test]# echo $RESULT
hello.sh test1.txt test2.txt
2.3 Location parameter variables

Main parameters for the position variable parameter value takes the script, the following syntax

Variable name Features
$n n is a number that represents the command itself $ 0, $ 1-9 represents a first parameter to the ninth, ten or more parameters needed braces comprising, as the 10th parameter is $ {10}
$* Represent all the command line parameters, the parameters as a whole
$@ Represent all the command line parameters, the parameters of each treated separately
$# It indicates the number of all parameters on the command line

Case:

Two input parameters, and calculating the number of two and printouts

[root@heimatengyun test]# vi sum.sh
#sum
#!/bin/bash
#分别接收2个参数
num1=$1
num2=$2
#求和
sum=$(($num1+$num2))
#打印
echo $sum

Save and exit, execute the script input two numbers to view the results

[root@heimatengyun test]# bash sum.sh 1 2
3
2.4 predefined variables

Predefined variables have a special role in the reference table

variable name Features
$? It represents the current process directly returns to the state of the last command. 0: successfully executed; non 0: execution failed
$$ The current process ID (PID)
$! Running in the background process ID of the last process (PID)

Case:

(1) view the current process and the last process running in the background

[root@heimatengyun test]# vi mypid.sh 
#!/bin/bash
#输出当前进程PID,也就是当前脚本运行时生成的PID
echo "当前进程PID=$$"
echo "最后一个后台进程PID=$!"

Save and exit, execute scripts

[root@heimatengyun test]# bash mypid.sh 
当前进程PID=7810
最后一个后台进程PID=

We can see the difference between $$ and $!, And $$ represent the current process PID, and $! Is the background represents the most runs of a process of PID.

(2) Output current process PID, and view the results of the last command

[root@heimatengyun test]# vi pid.sh
#!/bin/bash
#输出当前进程PID,也就是当前脚本运行时生成的PID
echo "当前进程PID=$$"
#通过ls命令,查找不存在的文件,&表示让命令后台执行
ls -l XXX.txt&
echo "最后一个进程PID=$!"
echo "最后一条命令执行结果:$?"

Save and exit, execute scripts

[root@heimatengyun test]# bash pid.sh 
当前进程PID=7395
最后一个进程PID=7396
最后一条命令执行结果:0
[root@heimatengyun test]# ls: cannot access XXX.txt: No such file or directory

[root@heimatengyun test]# 

We can see the process and the current process command script is not the same, and although xxx.txt file does not exist, but the result still returns to zero. If you instead look for a file that already exists, no doubt, be sure to return the result is still zero. That is on top of the script regardless of whether the command is executed successfully, will return 0 because the current process can only get to by & let command executed in the background, in fact, opened a new process, and $? Last execution results of the command, Therefore, in order to make a judgment whether success is especially to be careful.

Operators and Expressions 2.2

grammar:

(1) $ ((expression)) or $ [expression]

(2) expr m + n note include a space between the operator expr

Case:

(1) $ (()) to achieve two numbers together

[root@heimatengyun test]# S=$((2+3))
[root@heimatengyun test]# echo $S
5

(2) $ [] to achieve two numbers together

[root@heimatengyun test]# SUM=$[2+3]
[root@heimatengyun test]# echo $SUM 
5

(3) command is implemented using two numbers together expr

[root@heimatengyun test]# S1=`expr 2 + 3` 
[root@heimatengyun test]# echo $S1
5

Note expr command, the operator must have spaces between, computation is performed or not, but the connection string, the following example demonstrates the spaces spaces and without distinction, since the additional multiplication sign * wildcard conflict, and therefore need \ escape

[root@heimatengyun test]# expr 2 + 3
5
[root@heimatengyun test]# expr 2+3
2+3
[root@heimatengyun test]# expr 2\*3
2*3
[root@heimatengyun test]# expr 2 \* 3
6
[root@heimatengyun test]# expr 2 * 3 
expr: syntax error

(4) Calculation expr command "multiplied by 2 and 3 plus 5"

[root@heimatengyun test]# S2=`expr 2 + 3`
[root@heimatengyun test]# echo $S2
5
[root@heimatengyun test]# expr $S2 \* 5
25

Note that the spaces between the operator, the above step of computing, one step may be directly calculated, attention needs to be escaped is nested backquotes, as follows:

[root@heimatengyun test]# expr `expr 2 + 3` \* 5
25
[root@heimatengyun test]# echo `expr \`expr 2 + 3\` \* 5`
25

2.3 conditional statement

2.3.1 using conditional substantially

Syntax: [condition]

Description: Conditions must be a space before and after, is not empty returns true, you can use $ verification? (0: true, non-0: false)

Case:

(1), respectively, and the variable determining the presence of absence of test return value

[root@heimatengyun test]# [ $HOME ]  
[root@heimatengyun test]# echo $?    
0
[root@heimatengyun test]# [ $TEST ]      
[root@heimatengyun test]# echo $?    
1

Since the $ HOME environment variable is certainly exist, and therefore returns 0, indicating conditions are met, the variable is not empty; but because no TEST variable is defined, it does not exist, it returns a non-zero.

(2) logic for determining conditional statement

[root@heimatengyun test]# [ $HOME ]&& echo ok || echo notok
ok
[root@heimatengyun test]# [ $TEST ]&& echo ok || echo notok     
notok

It is similar to other languages ​​ternary operator, followed condition is satisfied statement execution or not performed.

Analyzing conditions used 2.3.2
  • A comparison between two integers
symbol meaning
= String comparison
-lt Less than
-the Less than or equal
-eq equal
-gt more than the
-give greater or equal to
-born not equal to
  • By file permissions judge
symbol meaning
-r Have permission to read
-w Have the authority to write
-x Have execute permissions
  • By file type judgment
symbol meaning
-f File exists and is a regular file
-d File exists and is a directory
-e File exists
  • Case

(1) Comparison integer

[root@heimatengyun test]# [ 1 -gt 2 ]
[root@heimatengyun test]# echo $?    
1

1 is not larger than 2, so the output 1, indicates false

(2) the file type is determined

[root@heimatengyun test]# [ -f test1.txt ]
[root@heimatengyun test]# echo $?
0
[root@heimatengyun test]# [ -f xxxx.txt ]     
[root@heimatengyun test]# echo $?        
1

test1.txt file exists, the output of 0 indicates true; xxxx.txt the file does not exist, the output represents a false

(3) determine the file permissions

[root@heimatengyun test]# ll
-rw-r--r--. 1 root root   9 Nov 30 20:43 test1.txt
[root@heimatengyun test]# [ -x test1.txt ]
[root@heimatengyun test]# echo $?
1

Since no test1.txt execute permissions, so it returns 1, indicating false

2.4 flow control statements

Flow control structure is divided into: sequential structure, branched structure, cyclic structure. Order to perform the sequential order sentence structure, a branched structure is determined in accordance with different operating conditions of the branch, the cyclic structure is determined whether loop is executed according to the conditions.

2.4.1 branch statement

Branch statement is divided into: if judge, case statements

  • if the judge

grammar:


if [Condition judging]

then

Program

be


Then written to or after the determination condition, separated by commas, the statement is equivalent to the top

if [Condition judging]; then

Program

be


if the judge may also be nested, form:

if [Condition 1 is determined]

then

Program 1

elif [determination condition 2]

​ then

Program 2

else

Program 3

be


Description: conditional statement, notice must be a space between the front bracket and if, before and after the brackets must have spaces

Case:

From the age of keyboard input, returns a different language to describe age

[root@heimatengyun test]# vim if.sh
#!/bin/bash
read -p "请输入您的年龄:" AGE
if [ $AGE -le 18 ];then
      echo "未成年"
  elif [ $AGE -le 30 ];then
      echo "年轻气盛"
  else
      echo "糟老头子"
fi

Use vim editor to edit the content (using vim vim here it is because more than vi suitable programming environments, error messages and other functions, it is recommended to write scripts using vim), save and exit and execute the script

[root@heimatengyun test]# bash if.sh 
请输入您的年龄:16
未成年
[root@heimatengyun test]# bash if.sh 
请输入您的年龄:40
糟老头子

As used herein, the read command to read keyboard input, -p parameter indicates the contents of the display prompt.

  • case statement

grammar:


case $ variable in

​ " 值1")

Statement 1

​ ;;

​ " 值2")

Statement 2

​ ;;

​ *)

Statement

​ ;;

esac


Case:

The arguments passed to the script outputs corresponding English 1,2,3

[root@heimatengyun test]#vim case.sh
#!/bin/bash
case $1 in
  1)
    echo one
    ;;
  2)
    echo two
    ;;
  3)
    echo three
    ;;
  *)
    echo "error"
    ;;
esac

Save and exit and execute

[root@heimatengyun test]# bash case.sh 1
one
[root@heimatengyun test]# bash case.sh 2
two
[root@heimatengyun test]# bash case.sh 3
three
[root@heimatengyun test]# bash case.sh 8
error
2.4.2 Loops

Loop divided: for loops, while loops

  • for loop

There are two formats for loop syntax, are as follows:

Syntax 1:


values ​​for variables in the binary value 1 ... 3

​ do

Program

​ done


Syntax 2:


for ((initial value; circulation control condition; variable change))

do

Program

​ done


Case:

(1) three times a day to say hello

[root@heimatengyun test]#vim greeting.sh 
#!/bin/bash
for time in morning afternoon evening
  do
     echo "good $time"
  done

Save and exit script execution greetings, greetings output statement

[root@heimatengyun test]# bash greeting.sh 
good morning
good afternoon
good evening

(2) a request for loop and to accumulate 5

[root@heimatengyun test]# vim getsum.sh
#!/bin/bash
sum=0
for ((i=0;i<=5;i++))
   do
     sum=$(($i+$sum))
   done
echo "sum=$sum"

Save and exit, and execute the script

[root@heimatengyun test]# bash getsum.sh 
sum=15
  • while loop

grammar:


the while [conditional formula]

​ do

Program

​ done


Case:

(1) to find an additive and the while loop 5

[root@heimatengyun test]# vim while.sh  
#!/bin/bash
i=1
sum=0
while [ $i -le 5 ]
    do
     sum=$[$i+$sum]
     i=$[$i+1]
    done
echo "sum=$sum" 

Save and execute

[root@heimatengyun test]# bash while.sh 
sum=15

note:

1, is assigned to the variable on the left do not add the $ sign, such as i = $ [$ i + 1] can not be written $ i = $ [$ i + 1], otherwise an error "command not found"

2, there are spaces between conditional brackets with the keyword, the first interior, operator and operand statement note left bracket

3, i = $ [$ i + 1], if wrongly written as i = $ i + 1 will error "integer expression expected".

2.5 Functions

Function is a function of the package, may provide code reuse. Functions are divided into system functions and user-defined functions for system function can be directly used to use, custom functions are written according to specific needs.

2.5.1 System functions

Use the existing system functions can improve efficiency, due to limited space, only a brief two system functions associated with file paths, specific use may also function to query specific usage by man command described earlier.

  • basename

grammar:

the basename [file path or string] [suffix]

Functional Description:

Remove all prefixes, including the last /, then the print string; specify the suffix is ​​then removed on the basis of the suffix.

Case:

[root@heimatengyun test]# basename "sdf/sdf/sdf"
sdf
[root@heimatengyun test]# basename /root/test/test1.txt 
test1.txt
[root@heimatengyun test]# basename /root/test/test1.txt txt
test1.
[root@heimatengyun test]# basename /root/test/test1.txt .txt
test1
  • dirname

grammar:

dirname absolute file path

Functional Description:

Remove the file name from the given file name contains the absolute path, then return to the path in force. It simply is to remove the non-directory part, returns to preserve the directory section, but does not include the final /

Case:

[root@heimatengyun test]# dirname /root/test/test1.txt    
/root/test
2.5.2 Custom Functions

grammar:


[Function] Function name [()]

{

Statements;

[Return Return value;]

}


Description:

(1) shell is interpreted rather than compiled executables, therefore the statement that the function must be declared before the function call execution line by line.

(2) function return values ​​only? Available through system variables $. You can display add a return statement returns (returns the value range 0-255), otherwise it will run the last command returns the result as a return value.

Function part, parameters within the brackets, the return value may be optional. function show () and function show and show () All forms are possible.

Case:

(2) an input integer, smaller than the input print out an integer

[root@heimatengyun test]# vim function.sh  
#!/bin/bash
function printNumber()
{
  i=0;
  while [ $i -lt $1 ]
  do
     echo $i;
     i=$[$i+1];
#    i=`expr \`expr $i + 1 \``     
     sleep 1;
  done
  return 0;
}
read -p "请输入一个数:" n;
printNumber $n;

Save the file and execute scripts

[root@heimatengyun test]# bash function.sh 
请输入一个数:5
0
1
2
3
4

Third, the preparation of Shell scripts

By demonstrating on top of the basic already can write a simple shell script, shell scripts This section explains reception determination user parameters and user parameters.

Receiving user parameters 3.1

Linux command mentioned before, the ability to employ various combinations of parameters necessary to perform specific functions is the measure of whether the command master the standards. Similarly, the function or script also needs to interact with the user, the user can flexibly handle parameters.

2.3 As already mentioned in the variable parameters for receiving several shell-site: ... $ 1, $ *, $ @ $ #

The following presentations with case

[root@heimatengyun test]# vim para.sh
#!/bin/bash
echo "当前脚本名称:$0"
echo "总共有$#个参数,分别为:$*"
echo "第一个参数为:$1,第三个参数为:$3"

Save the script, and execute

[root@heimatengyun test]# bash para.sh 1 2 3
当前脚本名称:para.sh
总共有3个参数,分别为:1 2 3
第一个参数为:1,第三个参数为:3

It can be seen directly with parameters after the script name, separated by a space between the parameters, you can get directly to the parameter at various locations within the script

3.2 Analyzing User Parameters

shell script conditional statement can be used to determine whether an expression inception, returns 0 if the condition holds true, otherwise it returns a random number other than 0 represents false. Determination of different objects, can be divided into the following four statements determination: test document sentence, the test logic statements, comparison statements integer value, a string comparison statements.

3.2.1 Test file statements

I.e., the test file is present or whether a permission condition determining satisfies the specified file, the file specific test parameters were as follows

Operators effect
-d Test whether the file is a directory type
-e Test whether a file exists
-f To determine whether the general file
-r To test whether the current user has read access
-w To test whether the current user has write permissions
-x To test whether the current user has permission to execute

Case:

Determine whether the types of files directory

[root@heimatengyun test]# [ -d /root/test ]
[root@heimatengyun test]# echo $?
0
[root@heimatengyun test]# [ -d /root/test/test1.txt ]
[root@heimatengyun test]# echo $?
1

First statement to determine through testing conditions, then use the shell interpreter built-in $? Variable to view the results. Since the / root / test directory, it returns 0; test1.txt file, it returns 1.

3.2.2 Test logic statements

Logic statements for logical analysis of the test results, different effects can be achieved according to test results. Logical operators are as follows:

Operators effect
&& After the surface of the current command execution logic and success, represents only performed behind the command
|| Or logic, indicating that the command will be executed after the current command behind the surface fails
Non-logic, the test represents the result of the determination condition negated.

Case:

判断当前登录用户是否为管理员

[root@heimatengyun test]# [ ! $USER = root ] && echo "user" || echo "root"
root
3.2.3 整数值比较语句

整数比较运算符仅是对数字的操作,不能将数字与字符串、文件等内容一起操作,而且不能想当然地使用日常生活中的等号、大于号、小于号等来进行判断。

ps:等号与赋值命令符冲突,大于小于号分别与输出输入重定向命令符冲突。因此一定要按照规范的整数比较运算符来进行操作。

可用的整数比较运算符如下表:

运算符 作用
-eq 是否等于
-ne 是否不等于
-gt 是否大于
-lt 是否小于
-le 是否小于或等于
-ge 是否大于或等于

案例:

[root@heimatengyun test]# [ 1 -lt 2 ]
[root@heimatengyun test]# echo $?    
0
[root@heimatengyun test]# [ 1 -gt 2 ]  
[root@heimatengyun test]# echo $?    
1
3.3.4 字符串比较语句

字符串比较语句用于判断测试字符串是否为空或两个字符串是否相等。常用来判断某个变量是否未被定义,即内容为空值。字符串常见运算符如下表:

运算符 作用
= 比较字符串内容是否相同,相同为0
!= 比较字符串内容是否不同,不同为0
-z 判断字符串内容是否为空,空则为0

案例:

分别查看存在和不存在的变量,区别返回值

[root@heimatengyun test]# echo $USER
root
[root@heimatengyun test]# echo $TEST

[root@heimatengyun test]# [ -z $USER ]
[root@heimatengyun test]# echo $?
1
[root@heimatengyun test]# [ -z $TEST ]
[root@heimatengyun test]# echo $?     
0

至此,shell编程相关知识就介绍完毕,下一篇文章继续学习与用户和文件、权限相关的知识。

Guess you like

Origin www.cnblogs.com/heimatengyun/p/12212706.html