Study Notes: twenty-three CentOS7 learning: -shift parameters left out of the loop - using functions

Study Notes: twenty-three CentOS7 learning: -shift parameters left out of the loop - using functions


This paper used to record learning experience, experience, also offering the use of notes, review courses to facilitate future. Complete Reference content of the basic science of God education materials, mostly drawn from self-images of God educational materials, in this very grateful to quality teaching and learning God MK teacher education. When you want to learn because of the needs to be reproduced, to declare the source of education for the school of God, Thank you!


23.1 out of the loop

In the process we use a loop statement cycle, it is sometimes necessary is not reached forced out of the loop when the loop end condition, then Shell has provided us with two commands to implement this feature: break and continue

23.1.1 break和continue

Break: out of the whole cycle

Continue: Skip this cycle, for the next cycle

  • break Overview: out of the current cycle or the entire end of the current cycle, for, while circulatory statement, breaks out statement after the loop body is currently located, loop body is executed, if no tax increases later, out of the current cycle represents the equivalent at break 1, can also be added after the number, it is assumed break 3 represents a third layer out of cycle

  • continue Overview: ignore this cycle the remainder of the code, directly next cycle; in for, while the other loop, out of a current loop is located, the line following the loop, if the latter number is added 1, 2 cycles is ignored in this condition represents conditions cycle, if it is 2, then, ignoring down

Example 1: Write a shell menu when exiting 4:00 press the number keys, otherwise the cycle has been displayed


[root@centos-7-24 tmp]# vim break-continue.sh
#!/bin/bash

while true
do
        echo "**************************"
        echo "please select your choice:"
        echo "1 copy"
        echo "2 delete"
        echo "3 backup"
        echo "4 quit"
        echo "**************************"
        read op
        case $op in
                1|copy)
                continue # 这里加了continue后,后面的echo语句就不会执行了
                echo "your choice is copy"
                ;;
                2|delete)
                echo "your choice is delete"
                ;;
                3|backup)
                echo "your choice is backup"
                ;;
                4|quit)
                echo "EXIT.."
                exit
                ;;
                *)
                echo "invalid selection, please try again"
        esac
done

[root@centos-7-24 tmp]# bash break-continue.sh 
**************************
please select your choice:
1 copy
2 delete
3 backup
4 quit
**************************
1
**************************
please select your choice:
1 copy
2 delete
3 backup
4 quit
**************************
2
your choice is delete
**************************
please select your choice:
1 copy
2 delete
3 backup
4 quit
**************************
3
your choice is backup
**************************
please select your choice:
1 copy
2 delete
3 backup
4 quit
**************************
4
EXIT..

Example 2: Batch Method using an interactive user to add


[root@centos-7-24 tmp]# vim adduser.sh 

#/bin/bash

while true
do
        read -p "please input prefix & password & num:" pre pass num
# 读取添加用户的前缀、通用密码、个数
        printf "user information:
        **********************
        user prefix: $pre
        user password: $pass
        user num: $num
        **********************
        "

        read -p "Are you sure?[y/n]" action # 读取用户互动选择
        if [ $action == "y" ]; then
                break
        else
                echo "please input your information again"
        fi
done

for i in $(seq $num)
do
        user=${pre}${i} # 定义用户名为前缀名加数字
        id $user &> /dev/null
        if [ $? -ne 0 ]; then # 判断用户是否已经存在,不存在则添加用户
                useradd $user
                echo "$pass"|passwd --stdin $user &> /dev/null
                if [ $? -eq 0 ]; then
                        echo -e "\033[31m$user\033[0m creat" # 以红色显示用户名
                fi
        else
                echo "user $user was already existed"
        fi
done

[root@centos-7-24 tmp]# bash adduser.sh 
please input prefix & password & num:yang 112233 4
user information:
    **********************
    user prefix: yang
    user password: 112233
    user num: 4
    **********************
    Are you sure?[y/n]y
yang1 creat
yang2 creat
yang3 creat
yang4 creat
[root@centos-7-24 ~]# grep yang* /etc/passwd # 查看发现用户添加成功
yangjie:x:1000:1000:yangjie:/home/yangjie:/bin/bash
yang1:x:1001:1001::/home/yang1:/bin/bash
yang2:x:1002:1002::/home/yang2:/bin/bash
yang3:x:1003:1003::/home/yang3:/bin/bash
yang4:x:1004:1004::/home/yang4:/bin/bash

Extended: seq command: seq command for generating the number of all integers from one to another between a number of


[root@centos-7-24 tmp]# seq 6
1
2
3
4
5
6

23.2 Shift Left instruction parameters

movement of the shift command parameters (left), usually for sequentially through each parameter without knowing the number of parameters is then passed corresponding processing (common in various Linux startup script programs)

When scanning parameter processing script, and often use the shift command, if your script needs more than 10 or 10 parameters, you will need to use the shift command to access the parameters of the first 10 and later

Effect: Each time, a position left sequentially parameter sequence, minus the value of $ # 1, the parameters of processing each parameter, shift out, is no longer available

Example: Addition Calculator


[root@centos-7-24 tmp]# vim shift.sh

#!/bin/bash

if [ $# -le 0 ]; then
# 判断参数是否大于0,大于0则执行加法程序
        echo "没有足够的参数"
else
        sum=0 # 设置sum初始值为0
        while [ $# -gt 0 ]; do
        # 当参数值大于0时,依次将参数1与sum相加,并且左移参数
                sum=$(($sum+$1))
                shift
        done
        echo "result is $sum" 
fi

[root@centos-7-24 tmp]# bash shift.sh 11 22 33 44
result is 110

23.3 Use function

Function is a script block of code, you can customize it named, and this function can be used anywhere in a script, you want to use this function, simply use the function name on it. The benefits of using the function: modular, code readability strong.

23.3.1 Creating function syntax

method 1:

function name {

commands

}

Note: name is the only name of the function

Method 2: brackets behind the name that you're defining a function

name(){

commands

}

Call the function syntax:

Function name Parameter 1 Parameter 2 ...

When you call the function, you can pass parameters. In function using $ 1, $ 2 ... to reference parameters

23.3.2 Use function

Example 1:


[root@centos-7-24 tmp]# vim fun1.sh

#!/bin/bash

function fun_1 { # 定义函数
        echo "this is function1"
        }
fun_2(){
        echo "this is function2"
        }
        fun_1 # 调用函数
        fun_2

[root@centos-7-24 tmp]# bash fun1.sh
this is function1
this is function2
    

Note: Using the function name, if you define a duplicate function name in a script, then subject to final

Example 2:


[root@centos-7-24 tmp]# vim fun2.sh

#!/bin/bash

function fun_1 { # 定义函数
        echo "this is function1"
        }
fun_1(){
        echo "this is function2"
        }
        fun_1 # 调用函数


[root@centos-7-24 tmp]# bash fun2.sh
this is function2

23.3.3 Return Values

Use the return command to exit the function and return to a specific exit code

Example 1:


[root@centos-7-24 tmp]# vim fun3.sh

#!/bin/bash

fun1(){
        echo "this is function"
        ls -al /etc/passwd
        return 3
        }

fun1

[root@centos-7-24 tmp]# bash fun3.sh
this is function
-rw-r--r--. 1 root root 2643 7月   3 23:36 /etc/passwd
[root@centos-7-24 tmp]# echo $? # 查看上个命令的返回码,发现为3
3

NOTE: To determine the status code will need to run on the end of a function return value is returned; status code range (0 to 255)

exit and return digital digital difference?

exit to exit the entire script, digital back; return just add the last line in the function, and then return figures, only to later execute command does not function, can not be forced to exit the entire script.

23.3.4 function of the value assigned to variables

Example: function name is equivalent to a command

[root@centos-7-24 tmp]# vim fun4.sh

#!/bin/bash

fun1(){
        read -p "input a value:" a
        echo $[$a*5]
}

num=$(fun1)
echo "current num is $num"

[root@centos-7-24 tmp]# bash fun4.sh
input a value:4
current num is 20

23.3.5 the transfer function

The first: passing parameters to the parameters in the function position via a script $ 1


[root@centos-7-24 tmp]# vim +8 fun5.sh 

#/bin/bash

fun1(){
        sum=$[5*$1]
        echo "the result is $sum"
        }

fun1 $1 # 执行fun1带有参数1

[root@centos-7-24 tmp]# bash fun5.sh 10
the result is 50

The second: direct pass parameters when calling the function


[root@centos-7-24 tmp]# vim fun6.sh

#/bin/bash

fun1(){
        sum=$[5*$1]
        echo "the result is $sum"
        }

fun1 5 #直接传参数5

[root@centos-7-24 tmp]# bash fun6.sh
the result is 25

Third: the function and use of multi-parameter passed


[root@centos-7-24 tmp]# vim fun7.sh

#/bin/bash

fun1(){
        sum1=$[5*$1]
        sum2=$[4*$2]
        echo "the result is $sum1, $sum2"
        }

fun1 $1 $2

[root@centos-7-24 tmp]# bash fun7.sh 6 7
the result is 30, 28

23.3.7 process variable function

Function variable type used in two ways:

  • Local variables
  • Global Variables

1, global variables, by default, you define a variable in the script are global variables, variables defined outside the function you can use within the function


[root@centos-7-24 tmp]# vim fun8.sh

#!/bin/bash

fun1(){
        sum=$[$var*2]
        }



fun1
echo "1-$sum"
read -p "input the value:" var
fun1
echo "2-$sum"
              
[root@centos-7-24 tmp]# bash fun8.sh 
fun8.sh:行4: *2: 语法错误: 期待操作数 (错误符号是 "*2")
1-
input the value:4
2-8
# 在var没有赋值之前,调用fun1,会报错,但是在var赋值之后调用fun1,发现var和sum均为脚本内的全局变量

23.4 Practical Application - Automatic backup mysql database script and nginx service startup scripts

23.4.1 Automatic backup mysql database script

1, to create a lab environment using mariadb

[root@centos-7-24 tmp]# systemctl start mariadb #启动mariadb
[root@centos-7-24 tmp]# mysqladmin -u root password "123456" #给root用户配置一个密码
[root@centos-7-24 tmp]# mysql -u root -p123456  #登录数据库
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 5
Server version: 5.5.60-MariaDB MariaDB Server

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> showd databases;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax t
o use near 'showd databases' at line 1MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.01 sec)

MariaDB [(none)]> create database yang; #创建数据库yang
Query OK, 1 row affected (0.00 sec)

MariaDB [(none)]> use yang # 切换到数据库yang
Database changed
MariaDB [yang]> create table user (id int); #创建表user,里面只有1列id字段类型为int
Query OK, 0 rows affected (0.10 sec)

MariaDB [yang]> insert into user value(1); # 插入一条记录,id字段值1
Query OK, 1 row affected (0.00 sec)

MariaDB [yang]> insert into user value(2); # 插入一条记录,id字段值2
Query OK, 1 row affected (0.00 sec)

MariaDB [yang]> select * from user; # 查看表中数据
+------+
| id   |
+------+
|    1 |
|    2 |
+------+
2 rows in set (0.00 sec)

MariaDB [yang]> exit;

2, mysql automated backup script:

[root@centos-7-24 tmp]# vim sqlbackup.sh
#!/bin/bash

# auto backup mysql
pre=`date +"%Y%m%d"`
backdir=/data/backup/mysql/$pre
# 定义备份路径
mysqldb=yang
mysqlusr=root
mysqlpw=123456
# 定义备份使用的用户名,密码,数据库名

if [ $UID -ne 0 ]; then
        echo "This script must use the root user!!"
        sleep 2
        exit 10
fi
# 脚本必须由root用户执行,否则自动退出

if [ ! -d $backdir ]; then
        mkdir -p $backdir
else
        echo "the backup file is alright existed!"
        exit 0
fi
# 判断备份文件夹是否存在,不存在则创建,存在则说明已经备份过,退出脚本

/usr/bin/mysqldump -u$mysqlusr -p$mysqlpw $mysqldb > $backdir/${mysqldb}_db.sql

# 备份数据库

[ $? -eq 0 ] && echo "the $pre MYSQL backup is success " || echo "backuo failed"
# 判断备份是否成功

cd /data/backup/mysql/ && tar -czvf ${pre}${mysqldb}.tar.gz $pre
# 压缩归档备份文件

find -mtime +30 -name "*.tar.gz" -exec rm -rf {} \;
find -type d -mtime +30 -exec rm -rf {} \;
# 删除30天前的归档文件和备份文件夹

[root@centos-7-24 tmp]# bash sqlbackup.sh 
the 20190704 MYSQL backup is success 
20190704/
20190704/yang_db.sql
[root@centos-7-24 tmp]# cd /data/backup/mysql/
[root@centos-7-24 mysql]# ll
总用量 4
drwxr-xr-x. 2 root root  25 7月   4 22:09 20190704
-rw-r--r--. 1 root root 800 7月   4 22:09 20190704yang.tar.gz
[root@centos-7-24 mysql]# cd 20190704/
[root@centos-7-24 20190704]# ll
总用量 4
-rw-r--r--. 1 root root 1795 7月   4 22:09 yang_db.sql
[root@centos-7-24 tmp]# bash sqlbackup.sh
the backup file is alright existed!

23.4.2 nginx service startup script

This script uses the function nginx features that make the script more readable

There is no example to install nginx service, directly learn of God annotate


[root@xuegod63 ~]# vim /etc/init.d/nginx    
#!/bin/bash
#chkconfig: 2345 80 90
#description:nginx run

# nginx启动脚本
# @author   Devil
# @version  0.0.1
# @date     2018-05-29

PATH=/data/soft/nginx
DESC="nginx daemon"
NAME=nginx
DAEMON=$PATH/sbin/$NAME   #/data/soft/nginx/sbin/nginx
CONFIGFILE=$PATH/$NAME.conf
PIDFILE=$PATH/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
[ -x "$DAEMON" ] || exit 0 # 判断是否存在可执行的nginx脚本文件,不存在则退出
do_start() # 定义函数
{
    $DAEMON -c $CONFIGFILE || echo -n "nginx already running" 
# 启动不成功则打印。。。
}
do_stop()
{
    $DAEMON -s stop || echo -n "nginx not running"
# 停止不成功则打印。。。
}
do_reload()
{
    $DAEMON -s reload || echo -n "nginx can't reload"
# 重启不成功则打印。。。
}
case "$1" in # 根据参数1的值选择不同的分支进行执行
    start)
        echo -n "Starting $DESC: $NAME"
        do_start
        echo "."
    ;;
    stop)
        echo -n "Stopping $DESC: $NAME"
        do_stop
        echo "."
    ;;
    reload|graceful)
        echo -n "Reloading $DESC configuration..."
        do_reload
        echo "."
    ;;
    restart)
        echo -n "Restarting $DESC: $NAME"
        do_stop
        do_start
        echo "."
    ;;
    *)
        echo "Usage: $SCRIPTNAME {start|stop|reload|restart}" >&2
        exit 3
    ;;
esac
exit 0

END
2019/7/4 22:47:15

Guess you like

Origin www.cnblogs.com/yj411511/p/11135413.html