Shell script --------shell variables, conditional expressions, flow control

Phase 3 Basics

Time: July 7, 2023

Participants: the whole class

Contents:

Shell variables, conditional expressions, flow control

Table of contents

1. Shell variables

Two, shell conditional expressions and operators

Three, break and continue statement

Demo: break statement

continue statement

4. Example expansion

Example 1: Set up a script to view server-related information

Example 2: View the total size of files ending with .sh in the system

Example 3: Create 10 users and set 6-digit random passwords

Example 4: Find the prime numbers within 100

Example 5: Read a file line by line


1. Shell variables

1. Introduction to shell variables

Variables are an essential part of any programming language, and variables are used to store various data .

Scripting languages ​​usually do not need to specify the type when defining variables, just assign values ​​directly, and Shell variables also follow this rule.

In the Bash shell  , the value of each variable is a string , whether you use quotes or not when assigning the variable, the value will be stored in the form of a string; this means that the Bash shell does not distinguish between variable types by default, even if you assign integers and decimals to variables, they will be treated as strings

2. Define variables

There are three common ways to define variables in Shell:

variable=value

variable = 'value'     #what you see is what you get

variable = "value"    #escape

variable =`cat test`   #Execute the command and assign the command output to the variable  

The naming convention of shell variables is the same as that of most programming languages:

Variable names are composed of numbers , letters , and underscores ;

Must start with a letter or underscore;

Keywords in the shell cannot be used (reserved keywords can be viewed through the help command).

3. Using variables

aa="cjk"

echo $aa

cjk

echo ${aa}   

#It is recommended to add curly braces { } to all variables, which is a good programming practice

cjk

4. Delete variables

Use the unset command to delete variables

aa="cjk"

echo ${aa}

cjk

unset aa    #unset command cannot delete read-only variables

echo ${aa}

5. Variable type

When running the shell, three variables will exist at the same time:

local variable :

Local variables are defined in scripts or commands, and are only valid in the current shell instance. Programs started by other shells cannot access local variables.

Environment variables :

All programs, including programs started by the shell, can access environment variables, and some programs need environment variables to ensure their normal operation. Shell scripts can also define environment variables when necessary.

shell variables :

Shell variables are special variables set by shell programs. Some of the shell variables are environment variables and some are local variables, which ensure the normal operation of the shell

6. System variables

 Directly execute env and set at the command line prompt to view system or environment variables. env displays user environment variables , s et displays Shell pre-defined variables and user variables . It can be exported as user variables through exp r or echo .

Some commonly used system variables when writing shell scripts :

system variable name

System Variable Awareness

$SHELL

Default Shell

$HOME

current user home directory

$IFS

internal field separator

$LANG

default language

$PATH

default executable path

$PWD

Current directory

$UID

current user id

$USER

Current user

$HISTSIZE

The size of historical commands, the command execution time can be set through the HISTTIMEFORMAT variable

$RANDOM

Randomly generate an integer from 0 to 32767

$HOSTNAME

CPU name

Generate 8-digit random number: echo "$RANDOM"|md5sum|cut -c 1-8

The test is as follows:

7. Ordinary variables and environment variables

  • Ordinary variable definition: VAR=value
  • Temporary environment variable definition: export VAR=value
  • Variable reference: $VAR
  • Difference: The scope of the environment variable of the Shell process is the Shell process. When the export is imported into the system variable, the scope is the Shell process and its sub-processes. It is invalid to open another shell.

8. List of special variables (shell variables)

variable

the meaning  

$0

The filename of the current script

$n

Arguments passed to the script or function. n is a number indicating the number of parameters. For example, the first parameter is $1 and the second parameter is $2.

$#

The number of arguments passed to the script or function.

$*

$@

All parameters passed to the script or function.

$?

The exit status of the last command, or the return value of the function, will return 0 if successful, and return non-zero if failed

$$

The current shell process ID, for shell scripts, is the process ID where these scripts are located

Example: Test the meaning of the above symbols

test:

The shift command moves the parameter forward one bit
shift n shifts forward n bits

2. Shell conditional expressions and operators

9. Conditional expressions

expression

example

[ expression ]

[ 1 -eq 1 ]

[[ expression ]]

[[ 1 -eq 1 ]]

test expression

test 1 -eq 1 , equivalent to []

Note: There are spaces before and after the expression in brackets, otherwise an error will be reported!

example:

[ 1 -eq 1 ] && echo "true" || echo "false"

[ 1 -eq 2 ] && echo "true" || echo "false"

[1 -eq 2] && echo "true" || echo "false"

10. Integer Comparator

Comparator

describe

example

-eq, equal

equal

[ 1 -eq 1 ] is true

-ne, not equal

not equal to

[ 1 -ne 1 ] is false

-gt, greate than

more than the

[ 1 -gt 1 ] is false

-lt, lesser than

less than

[ 1 -lt 1 ] is false

-ge, greate or equal

greater than or equal to

[ 1 -ge 1 ] is true

-le, lesser or equal

less than or equal to

[ 1 -le 1 ] is true

test:

11. String comparator

operator

describe

example

==

equal

[ “a” == “a” ] is true

!=

not equal to

[ “a” != “a” ] is false

-n

True if string length is not equal to 0

VAR1=1;VAR2=”” 
[ -n “$VAR1” ]为 true 
[ -n “$VAR2” ]为 false

-z

字符串长度等于 0 为真

VAR1=1;VAR2=”” 
[ -z “$VAR1” ]为false
[ -z “$VAR2” ]为 true

注意:使用-n 判断字符串长度时,变量要加双引号,养成好习惯,字符串比较时都加上双引号

12、文件测试

测试符

描述

实例

-e

文件或者目录存在为真

[ -e path ] path 存在为 true

-f

文件存在为真

[ -f file_path ] 文件存在为 true

-d

目录存在为真

[ -d dir_path ] 目录存在为 true

-r

有读权限为真

[ -r file_path ]file_path有读权限为真

-w

有写权限为真

[ -w file_path ]file_path有写权限为真

-x

有执行权限为真

[ -x file_path ]file_path有执行权限为真

-s

文件存在且不为空为真

[-s file_path]file_path存在且不为空为真

测试:

13、布尔运算符

运算符

描述

实例

非关系,条件结果取反

[ ! 1 -eq 2 ]为true

-a

和关系,在[]表达式中使用

[ 1 -eq 1 -a 2 -eq 2 ]为true
两者都为真才为真

-o

或关系,在[]表达式中使用

[ 1 -eq 1 -o 2 -eq 1 ]为true
两者有一真则为真

测试:

14、逻辑判断符

判断符

描述

实例

&&

逻辑和,在[[]]表达式中或判断表达式是否为真时使用

[[ 1 -eq 1 && 2 -eq 2 ]]为 true
[ 1 -eq 1 ] && echo ‘true’
如果&&前面的表达式为true则执行后面的

||

逻辑或,在[[]]表达式中或判断表达式是否为真时使用

[[ 1 -eq 1 || 2 -eq 1 ]]为 true
[ 1 -eq 2 ] || echo ‘true’
如果||前面的表达式为false则执行后面的

测试:

15、整数运算符

运算符

描述

+

加法

减法

*

乘法

/

除法

%

取余

运算表达式

实例

$(())

$((1+1))

$[]

$[]

测试:

16、其他运算符

命令

描述

实例

let

赋值并运算

let x++;echo $x 每执行一次 x 加 1
let y–;echo $y 每执行一次 y 减 1
let x+=2 每执行一次 x 加 2
let x-=2 每执行一次 x 减 2

expr

乘法*需要\转义"\*"

expr 1 \* 2 运算符两边必须有空格
expr \( 1 + 2 \) \* 2 使用双括号时要转义

测试:

三、break和continue语句

  • continue 与 break 语句只能循环语句中使用;
  • break:终止循环,运行针跳至done后;
  • continue :跳出当前循环,运行针跳至do后,开始下一循环;

演示:
break语句

例:写一段循环执行的语句,给定最大值,然后测试,如下

测 试:

continue语句

例:将上述测试break改为continue,查看发生了哪些变化

测试:

四、实例拓展

实例1:设置查看服务器相关信息脚本

echo "主机名:`hostname`"

echo "IP地址:`ip a | grep "global" | cut -d "/" -f 1 | cut -d "t" -f 2 | tr -d "" ` "

echo "操作系统版本:`cat /etc/redhat-release`"

echo "内核版本:`uname -r`"

echo "CPU信息:`lscpu | grep -i "Mode1 name" | cut -c "24-69"`"

echo "内存总大小:`free -h | grep "Mem" | cut -d "M" -f 2 | tr -d "em:"`M"

测试:

实例二:查看系统内以.sh结尾的文件总大小

例:

sum=0

for i in `find / -type f -a -name "*.sh"`

do

        size=`ls -l $i | cut -d " " -f 5`

        let sum+=size

done

        echo ".sh结尾得到总大小为$(($sum/1024))kb"

测  试:

实例三:创建10个用户并设置6位随机密码

例:

for i in `seq 10`

do

        useradd user$i

        pass=`echo $RANDOM | md5sum |cut -c 1-6`

        echo "$pass" | passwd --stdin "user$i"

        echo -e "账户:user$i\n 密码:$pass" >> /root/passwd

done

测 试:

执行过程:

实例四:找出100以内的质数

例:

for i in `seq 100`

do

        for((j=2;j<i;j++))

        do

                [ $((i%j)) -eq 0 ] && break

        done

                [ $j -eq $i ] && echo $i

done

测 试:

实例五:逐行读取文件

例:

cat $1 | while read line

do

        echo "$line"

        sleep 1

done

测试:

Guess you like

Origin blog.csdn.net/2302_77582029/article/details/131678254