linux notes 3-vi editor, shell script, timing task

VIM text editor

Everything in a linux system is a file, so it is often necessary to edit the content of the file. People will install Vim text editing tool in Linux system. Vim is an upgraded version of vi.
There are three modes of vim:
Command mode: control cursor movement, delete, assign, and paste text.
Input mode: input text normally.
Last line mode: save, exit and set the editing environment
every time you run After vim enters the command mode by default, the three modes of switching are as follows:
Insert picture description here
Commonly used shortcut keys for command mode:

dd  删除(剪切)光标所在的行
5dd   删除(剪切)光标所在的行开始的5行
yy     复制光标所在的整行
5yy   赋值光标所在行开始的5行
p    将剪切赋值的行粘贴到光标后
/字符串   在文本中从上至下搜索该字符串
?字符串  在文本中自下而上搜索该字符串
n   显示搜索命令定位到下一个字符串
N   显示搜索命令定位到上一个字符串
u   撤销上一步操作

Common commands in the last line mode:

:w   保存
:q   退出
:q!  强置退出(放弃修改)
:wq!  强制保存退出
:set nu  显示行号
:set nonu  不显示行号
:整数    跳转到该行

All commands in command mode and last line mode are case sensitive

Configure the host name

[root@localhost ~]# vi /etc/hostname
server1

Configure network card information

[root@localhost ~]# vi /etc/sysconfig/network-scripts/ifcfg-ens33
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
IPADDR=192.168.12.10
NETMASK=255.255.255.0
GATEWAY=192.168.12.1
DNS=192.168.12.1
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens33
UUID=032e7ad3-cb98-49f1-ab3a-328e437aba77
DEVICE=ens33
ONBOOT=yes
[root@localhost ~]# systemctl restart network

Configure CD yum warehouse

Enter the directory /etc/yum.repos.d, the reference steps are as follows:
Insert picture description here

Shell script

Shell is the communication medium between the user and the Linux system. It also defines various variable parameters and provides the control structure features that are unique to high-level languages ​​such as loops and branches. How to use these functions is particularly important to give instructions accurately.
Shell works in two forms:
interactive: the user enters a command, Shell interprets and executes a
batch process: write a Shell script in advance, which contains many commands, and the Shell executes all the commands at once.
View Shell interpreters available in the system

[root@localhost yum.repos.d]# cat /etc/shells
/bin/sh
/bin/bash
/usr/bin/sh
/usr/bin/bash

View the current Shell interpreter

[root@localhost yum.repos.d]# echo $SHELL
/bin/bash

Compile a simple script

A complete script should include:
**Script statement (#!): ** Tell the system which shell is used to interpret
** Comment information (#): ** It is not necessary to introduce the execution statement or the program
** Executable statement : **Specific commands

Write a simple test.sh

[root@localhost test]# vi test.sh
#!/bin/bash
#example
pwd
ls -al
~

Three ways to execute scripts:
script file path: ./test.sh
sh script file path: sh test.sh
source script file path: source test.sh
execution example:

[root@localhost test]# ./test.sh
-bash: ./test.sh: 权限不够
[root@localhost test]# ll
总用量 4
-rw-r--r--. 1 root root 32 1021 04:58 test.sh
[root@localhost test]# chmod u+x test.sh
[root@localhost test]# ./test.sh
/root/test
总用量 4
drwxr-xr-x. 2 root root  21 1021 04:58 .
dr-xr-x---. 6 root root 234 1021 04:56 ..
-rwxr--r--. 1 root root  32 1021 04:58 test.sh
[root@localhost test]# sh test.sh
/root/test
总用量 4
drwxr-xr-x. 2 root root  21 1021 04:58 .
dr-xr-x---. 6 root root 234 1021 04:56 ..
-rwxr--r--. 1 root root  32 1021 04:58 test.sh
[root@localhost test]# source test.sh
/root/test
总用量 4
drwxr-xr-x. 2 root root  21 1021 04:58 .
dr-xr-x---. 6 root root 234 1021 04:56 ..
-rwxr--r--. 1 root root  32 1021 04:58 test.sh
[root@localhost test]# 

Receive user parameters

When the shell script is executed, you can pass in parameters, such as: test.sh p1 p2 In the
script, you can pass 1 − 9, 1-9,19,{10}, 11 , . . . {11},... 11,. . . {} N-access parameters corresponding to the position
in addition to the built-in shell script the following parameters:

$0 当前执行Shell脚本的程序名
$# 一共有多少个参数
$*  所有位置变量的值
$?  判断上一条命令是否执行成功 0 为成功 非0 表示失败

Write and execute the following script:

[root@localhost test]# vi test2.sh
#!/bin/bash
echo "当前脚本名称:$0"
echo  "总共$#个参数"
echo  "第一个参数$1"
echo  "所有位置变量的值 $*"
echo  "上一条是否执行结果$?"
[root@localhost test]# chmod u+x test2.sh
[root@localhost test]# ./test2.sh p1 p2 p3 p4
当前脚本名称:./test2.sh
总共4个参数
第一个参数p1
所有位置变量的值 p1 p2 p3 p4
上一条是否执行结果0

Judge user parameters

Shell scripts sometimes need to determine user input parameters, such as the mkdir command to determine whether the directory exists.
The judgment can be completed by conditional test statement, format: [Conditional expression] There are spaces on both sides.
Conditional test statement includes: file test, logic test, integer value comparison, string comparison

File test

Format: [Operator file or directory name]

-d  测试是否是目录
-e  测试文件或目录是否存在
-f   是否为文件
-r   测试当前用户是否有权读入
-w  测试当前用户是否有权限写入
-x   测试当前用户是否有权限执行 

Examples are as follows:

[root@bogon ~]# [ -d /etc/f ]
[root@bogon ~]# echo $?
1
[root@bogon ~]# [ -d /etc ]
[root@bogon ~]# echo $?
0
[root@bogon ~]# 

Logic test

Format: [Expression 1] Operator [Expression 2]

&&  逻辑与
||      逻辑或
!    逻辑非

If the current user is root, output root

[root@bogon ~]# [ $USER==root ] && echo "root"
root

Integer value test

Format: [integer 1 operator integer 2]
-eq is equal to
-ne is not fixed to
-gt is greater than
-lt is less than
-le is less than or equal to
-ge is greater than or equal to
Example:

[root@bogon ~]# [ 10 -gt 10 ]
[root@bogon ~]# echo $?
1

String comparison

Format: [String 1 Operator String 2]

=  字符串内容是否相同
!=  字符串内容是否不同
-z  字符串是否为空

Determine whether the string is empty:

[root@bogon ~]# [ -z '' ]
[root@bogon ~]# echo $?
0
[root@bogon ~]# [ -z '1' ]
[root@bogon ~]# echo $?
1

Conditional test statement

The conditional test statement allows the Shell script to flexibly adjust the work content according to the actual situation.

if statement

Single branch if
edit the script and execute
it to determine whether the testdir directory exists or not, create it if it does not exist

[root@localhost tmpdir]# vi test.sh
#!/bin/bash
DIR=testdir
if [ ! -e $DIR ]
then
mkdir -p $DIR
fi


[root@localhost tmpdir]# ./test.sh

Double branch if

Write the script test2.sh and test
it. If the ping command is executed successfully, the output address is available, otherwise the output address is unavailable

[root@localhost tmpdir]# vi test2.sh
#!/bin/bash
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
if [ $? -eq 0 ]
then
echo "HOST $1 is up"
else
echo "Host $1 is down"
fi

[root@localhost tmpdir]# ./test2.sh ww.baddi.com
Host ww.baddi.com is down

Multi-branch if

The user enters the score, and the Excellent Good Fail is output according to the score, as follows:

[root@localhost tmpdir]# vi test3.sh
#!/bin/bash
read -p "enter your score (0-100):" GRADE
if [ $GRADE -ge 85 ] && [ $GRADE -le 100 ] ; then
echo "Excellent"
elif [ $GRADE -ge 60 ] && [ $GRADE -le 85 ] ; then
echo "Good"
else
echo "Fail"
fi


[root@localhost tmpdir]# ./test3.sh 
enter your score (0-100):90
Excellent
[root@localhost tmpdir]# ./test3.sh 
enter your score (0-100):70
Good

for conditional statement

grammar:

for 变量名 in 取值列表
do 
    命令序列
done

Example:
Read the user from the file, if the user does not exist, create and set the entered password.
Create a text file user.txt with the following content

[root@bogon tmpdir]# vi user.txt
zhangsan
lisi
wangwu

Write the script as follows

[root@bogon tmpdir]# vi testfor.sh
#!/bin/bash
read -p "Enter The Users Password:" PASSWD
for UNAME in `cat user.txt`
do
  id $UNAME &>/dev/null
  if [ $? -eq 0 ]
  then
     echo "user $UNAME already exists"
  else
     useradd $UNAME &>/dev/null
     echo "$PASSWD" | passwd --stdin $UNAME &>/dev/null
     if [ $? -eq 0 ]
     then
       echo "create SUCCESS"
     else
       echo "create failed"
     fi
  fi
done
~

Results of the

[root@bogon tmpdir]# ./tetfor.sh
Enter The Users Password:123456789
create SUCCESS
create SUCCESS
create SUCCESS
[root@bogon tmpdir]# ./tetfor.sh
Enter The Users Password:zxm123
user zhangsan already exists
user lisi already exists
user wangwu already exists
[root@bogon tmpdir]# 

while statement

grammar

while 条件测试操作
do
    命令序列
done

Example
Randomly generate an integer in the range of 0~999, and then prompt the user to enter a number to make a guess. The program prompts whether it is high or low according to the guessing result. After the guess is successful, the program exits

#!/bin/bash
PRICE=$(expr $RANDOM % 1000)
TIMES=0
echo "数字在0-999之间,猜猜看是多少"
while true
do
    read -p "请输入:" INT
    let TIMES++
    if [ $INT -eq $PRICE ] ; then
        echo "猜对了,您共猜了 $TIMES 次"
        exit 0
    elif [ $INT -gt $PRICE ] ; then
        echo "高了!你再猜:"
    else
        echo "低了! 你再猜:"
    fi
done

case statement

According to different values ​​of variables, execute different command operation
syntax

case 变量值 in 
模式1)
   命令序列
   ;;
模式2)
    命令序列
    ;;
  ...... 
  *)
     默认命令序列
esac 

Example
Enter a character in Korean alphabet to determine whether it is a number or a letter, as follows:

        [root@bogon tmpdir]# vi testcase.sh 
#!/bin/bash
read -p "请输入yes或no 按Enter键确认:" KEY
case $KEY in
[a-z]|[A-Z])
    echo "您输入的是字母"
    ;;
[0-9])
    echo "您输入的是数字"
    ;;
*)
    echo “您输入的内容$KEY既不是字母也不是数字”
    ;;
esac

Scheduled Tasks

Scheduled tasks allow linux operations to execute programs automatically in accordance with time rules. Planning tasks are divided into one-time planning tasks and long-term planning tasks.

One-time scheduled task

Realized by atd service, operated by command at

at <时间>  安排一次性任务
atq 或 at -l  查看任务列表
at -c 序号 预览任务与设置环境
atrm 序号  删除任务

Example
If the command is not installed, execute yun install at to install. After
entering the at command, ctrl + d saves and exits.

[root@bogon ~]# at 15:30
at> echo `date`
at> 
job 1 at Tue Oct 20 15:30:00 2020
Can't open /var/run/atd.pid to signal atd. No atd running?
[root@bogon ~]# atq
1       Tue Oct 20 15:30:00 2020 a root

Long-term recurring planning tasks

Realize
command through crontab service

创建、编辑计划任务 crontab -e [ -u 用户名]
查看计划任务 crontab -l [ -u 用户名]
删除计划任务 crontab -r [ -u 用户名]

Timed task format:
minute (0-59) hour (0-23) day (1-31) month (1-12) week (0-7 07 are all Sundays) Command (script or command)

Example:
once per minute /root/tmpdir/task.sh script
defined tasks
when defining the task will be modified to 16 hours does not perform regular tasks has been changed to 4 to normal execution turned out to be the wrong time

[root@bogon ~]# crontab -e
5 4 * * 1  /root/tmpdir/task.sh
~

Task.sh script content
Write the current time to the date.txt file

#!/bin/bash
echo `date` >> /root/date.txt
[root@bogon ~]# 

date.txt output result

[root@bogon ~]# tail -f date.txt
Mon Oct 26 04:09:01 EDT 2020
Mon Oct 26 04:10:01 EDT 2020

If the scheduled task is not executed
1, check whether the crond service status is normal service crond status

[root@VM-0-9-centos mail]# service crond status
Redirecting to /bin/systemctl status crond.service
● crond.service - Command Scheduler
   Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2020-11-23 21:35:06 CST; 24h ago
 Main PID: 975 (crond)
   CGroup: /system.slice/crond.service
           └─975 /usr/sbin/crond -n

2. View the log
. The contents of the root file in the following directory will show the exceptions encountered during execution

[root@VM-0-9-centos mail]# pwd
/var/spool/mail
[root@VM-0-9-centos mail]# ll
total 16
-rw-------  1 root mail 13811 Nov 24 21:53 root
-rw-rw----. 1 rpc  mail     0 Aug  8  2018 rpc

Guess you like

Origin blog.csdn.net/zhangxm_qz/article/details/109231463