linux 快捷键汇总

 

1,快捷键

移动光标
Ctrl + a
Ctrl + e
Ctrl + f
Ctrl + b

剪切,粘贴,清楚
Ctrl + Insert   复制
Shift + Insert  粘贴
Ctrl + k     剪切光标到行尾
Ctrl + u     剪切光标到行首
Ctrl + w     剪切光标前1个单词
Ctrl + y     粘贴剪切的文本

控制快捷键
Ctrl + s     锁定屏幕,无法写入
Ctrl + q     解锁屏幕

!号开头的快捷命令
!!       执行上一条命令
!pw      执行最近以pw开头的命令*
!pw:p      执行最近以pw开头的命令*,仅仅是打印不执行
!num      执行历史命令列表的第num(数字)条命令
!$        上一条命令的最后一个参数,相当于 Esc+.(点)


 

 

&  表示任务在后台执行,如要在后台运行redis-server,则有  redis-server &

&& 表示前一条命令执行成功时,才执行后一条命令 ,如 echo '1‘ && echo '2'

| 表示管道,上一条命令的输出,作为下一条命令参数,如 echo 'yes' | wc -l,再如ps aux | grep nginx

|| 表示上一条命令执行失败后,才执行下一条命令,如 cat nofile || echo "fail"



Linux系统下Shell重复执行上条命令的 4 种方法:

1、使用上方向键,并回车执行。
2、按 !! 并回车执行。
3、输入 !-1 并回车执行。
4、按 Ctrl+P 并回车执行。

把一个命令的结果作为变量的内容赋值
变量名=`ls`
变量名=$(ls)

a=$(date +%F)
echo $a
echo $(data +%F).tar.gz
echo hello-$(data +%F).tar.gz

awk 'BEGIN {print "'$ETT'"}' #awk 加单引号后再同时添加双引号

常用特殊位置的参数变量
$0   获取当前执行的shell脚本名称,如果执行了脚本包含了路径,那么就包含脚本路径
$n   获取当前执行的shell脚本的第n个参数值, n=1..9 ,当n为0时表示脚本的文件名;如果n大于9,则用大括号括起来,例如$(10),接的参数以空格隔开
$#   获取当前shell脚本后面接的参数的总个数
$*   获取当前shell脚本所有传参的参数,不加引号和$@相同;如果加引号"$@",相当于"$1 $2 $3"
$@   获取当前shell脚本所有传参的参数,不加引号和$@相同;如果加引号"$*",相当于"$1" "$2" "$3"

ps1:$1
# cat p.sh 
echo $1
]# sh p.sh old 
old
ps2:$2 $3
]# cat p.sh 
echo $1 $2
]# sh p.sh log1 log2
log1 log2
ps3:\${1..15}, 当大于9的时候就不对了
[root@test01 ~]# echo \${1..15}
$1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15
[root@test01 ~]# echo \${1..15} >n.sh
[root@test01 ~]# cat n.sh 
$1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15
[root@test01 ~]# echo {a..z}
a b c d e f g h i j k l m n o p q r s t u v w x y z
[root@test01 ~]# sh n.sh {a..z}
n.sh: line 1: a: command not found
[root@test01 ~]# cat n.sh 
$1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15
[root@test01 ~]# vi n.sh 
[root@test01 ~]# cat n.sh 
echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15
[root@test01 ~]# sh n.sh {a..z}
a b c d e f g h i a0 a1 a2 a3 a4 a5  #当大于9的时候就不对了
当位置大于9时,需要用大括号将数括起来
]# cat n.sh 
echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} ${14} ${15}
[root@test01 ~]# sh n.sh {a..z}
a b c d e f g h i j k l m n o

  

 

脚本名及路径
# cat n.sh 
echo $0
[root@test01 ~]# sh n.sh 
n.sh
[root@test01 ~]# cat n.sh 
echo $0
[root@test01 ~]# sh n.sh 
n.sh
[root@test01 ~]# basename n.sh 
n.sh
[root@test01 ~]# dirname n.sh 
.
[root@test01 ~]# vi n.sh 
[root@test01 ~]# sh n.sh 
.
n.sh
[root@test01 ~]# cat n.sh 
dirname $0
basename $0

条件表达式判断语句
# cat t1.sh 
[ $# -ne 2 ] && {      #如果执行脚本传参的个数不等于2
  echo "muse two args"
  exit 1
}
echo hello
[root@test01 ~]# sh t1.sh 1 2
hello
[root@test01 ~]# sh t1.sh 1 
muse two args

if判断语句的语法
]# cat t2.sh 
if [ $# -ne 2 ]            #如果执行脚本传参的个数不等于2
  then
    echo "USAGE:/bin/sh $0 arg1 arg2"   #$0打印脚本名称
    exit 1
fi
echo $1 $2
[root@test01 ~]# sh t2.sh
USAGE:/bin/sh t2.sh arg1 arg2
[root@test01 ~]# sh t2.sh aa bb
aa bb

# set -- "hello world" aa nb
[root@test01 ~]# echo $#
3
[root@test01 ~]# echo $1
hello world
[root@test01 ~]# echo $2
aa
[root@test01 ~]# echo $3
nb
[root@test01 ~]# 
[root@test01 ~]# 
[root@test01 ~]# echo $*  
hello world aa nb
[root@test01 ~]# echo $#
3
[root@test01 ~]# echo $@
hello world aa nb
# for i in $*;do echo $i;done
hello
world
aa
nb

[root@test01 ~]# for i in $@;do echo $i;done
hello
world
aa
nb
[root@test01 ~]# for i in "$*";do echo $i;done
hello world aa nb
[root@test01 ~]# for i in "$@";do echo $i;done  #加双引号,这才是真正符合传入的参数需求
hello world
aa
nb

Shell特殊进场中的特殊状态变量
$?  获取执行上一个指令状态返回值,(0为成功,非零为失败)
$$  获取当前执行的shell脚本的进程号(PID),这个变量不常用,
$!  获取上一个在后台工作的进程的进程号(PID),不常用
$_  获取在此之前执行的命令或脚本的最后一个参数,不常用


bash中如何实现条件判断?

条件测试类型:

       整数测试

       字符测试

       文件测试

条件测试的表达式:

       [ expression ]

       ` expression `

       test expression      

整数比较:

       -eq(equal)     : 测试两个整数是否相等;比如 $A -eq $B

       -ne(inequality) : 测试两个整数是否不等;不等,为真;相等,为假;

       -gt(greter than) : 测试一个数是否大于另一个数;大于,为真;否则,为假;

       -lt(less than)  : 测试一个数是否小于另一个数;小于,为真;否则,为假;

       -ge(greter equal): 大于或等于

        -le(less equal) :小于或等于      

命令的间逻辑关系:

       逻辑与: &&

              第一个条件为假时,第二条件不用再判断,最终结果已经有;

              第一个条件为真时,第二条件必须得判断;

       逻辑或: ||   

如果用户不存在,添加并给密码;否则,显示其已经存在
~]# ! id xiaoming && useradd xiaoming && echo "xiaoming" |passwd --stdin xiaoming || echo "user exists"
uid=1000(xiaoming) gid=1000(xiaoming) groups=1000(xiaoming)
user exists

$$特殊变量,获取当前执行脚本的进程号
]# cat pid.sh
#!/bin/sh
pidpath=/tmp/a.pid
if [ -f "$pidpath" ]
  then
    kill `cat $pidpath` >/dev/null 2>&1
    rm -rf $pidpath
fi

echo $$ >$pidpath
sleep 300


echo命令
-n   不换行输出内容
-e   解析转义字符
(转义字符)
\n  换行
\r  回车
\t  制表符tab
\b  退格
\v  纵向制表符

# echo "hello\txiaoming\nhello2\txiaohong"
hello\txiaoming\nhello2\txiaohong
[root@test01 ~]# echo -e "hello\txiaoming\nhello2\txiaohong"  #加-e参数解析以"\"开头的字符
hello	xiaoming
hello2	xiaohong



eval 当执行到eval时,shell读入参数args,并将组合成一个新的命令。
# cat noeval.sh 
echo \$$#
[root@test01 ~]# sh noeval.sh arg1 arg2
$2
[root@test01 ~]# cat eval.sh 
eval "echo \$$#"
[root@test01 ~]# sh eval.sh arg1 arg2
arg2

exec 能够在不创建新的子进程的前提下,转去执行指定的命令,当指定命令执行完毕后,该进程结束。
~]# seq 5 >/tmp/tmp.log
[root@test01 ~]# cat /tmp/tmp.log
1
2
3
4
5
[root@test01 ~]# vim exec.sh
[root@test01 ~]# sh exec.sh 
1
2
3
4
5
ok
[root@test01 ~]# cat exec.sh 
exec </tmp/tmp.log
while read line
do
    echo $line
done
echo ok


shift 将位置参数$1、$2等进行左移,($1、$2左移后变成$2)
]# cat n.sh 
echo $1 $2
if [ $# -eq 2 ];then
    shift
    echo $1  
fi
[root@test01 ~]# sh n.sh 1 2 
1 2
2    #本来是1的,进行左移后变成2

变量值长度
通过在变量名前加#,就可以打印变量值的长度
]# a="I am xiaoming"
[root@test01 ~]# echo ${a}
I am xiaoming
[root@test01 ~]# echo $a
I am xiaoming
[root@test01 ~]# echo ${#a}
13

  

[root@test01 ~]# echo $a
I am xiaoming
~]# echo $a |wc -l
1
[root@test01 ~]# echo $a| wc -L   #-L  大写L可以,小写不行
13


]# echo ${a:2}  #截取变量的内容,从第2个字符之后开始截取后面全部
am xiaoming
[root@test01 ~]# echo ${a}
I am xiaoming
[root@test01 ~]# echo ${a:1}
am xiaoming
[root@test01 ~]# echo ${a:3}
m xiaoming
[root@test01 ~]# echo ${a:2:2} ##截取变量的内容,从第2个字符之后开始截取2个字符
am
[root@test01 ~]# echo ${a} | cut -c 3-4 #输出变量内容,管道交给cut 截取第3-4个位置的字符
am


]# echo ${b}
abcABC123ABCabc
[root@test01 ~]# echo ${b##a*c}  #从开头开始删除最长匹配"a*c"的子串  

[root@test01 ~]# echo ${b##a*C}  #从开头开始删除最长匹配"a*C"的子串  
abc

有关上述匹配删除的小结:
#  表示从开头删除匹配最短
## 表示从开头删除匹配最长
%  表示从结尾删除匹配最短
%%  表示从结尾删除匹配最短
a*c 表示匹配的字符串, * 表示匹配所有, a*c匹配a到c的字符串


":=" 代表同时赋值给里边外部的没有定义的变量
# echo $b

[root@test01 ~]# echo $bb

[root@test01 ~]# bb=${b:=unix}
[root@test01 ~]# echo $b
unix
[root@test01 ~]# echo $bb
unix
[root@test01 ~]# bb=${b=unix}
[root@test01 ~]# echo $bb
unix
[root@test01 ~]# echo $b
unix




使用-x可以跟踪详细的执行步骤
[root@test01 ~]# sh -x checkurl.sh 
+ CheckUrl
+ timeout=5
+ fails=0
+ success=0
+ true
+ wget --timeout=5 --tries=1 http://helloworld.com -q -O /dev/null
+ '[' 0 -ne 0 ']'
+ let success+=1
+ '[' 1 -ge 1 ']'
+ echo success
success
+ exit 0


expr计算
~]# expr 2 + 2
4
[root@test01 ~]# i=5
[root@test01 ~]# i=`expr $i + 6`
[root@test01 ~]# echo $i
11

~]# i=5
[root@test01 ~]# expr $i + 6 &>/dev/null 
[root@test01 ~]# echo $?
0         返回值0,为整数
[root@test01 ~]# i=xiaoming
[root@test01 ~]# expr $i + 6 &>/dev/null 
[root@test01 ~]# echo $?
2        返回值不为0,不是整数     

通过传参判断输出的内容是否为整数
[root@test01 ~]# sh expr1.sh 2
int
[root@test01 ~]# sh expr1.sh a
chars
[root@test01 ~]# cat expr1.sh 
#!/bin/sh
expr $1 + 1 >/dev/null 2>&1
[ $? -eq 0 ] && echo int || echo chars

通过read读入持续等待输入的例子
]# sh judge_int.sh 
Pls input: a
chars
Pls input: 11111
int
Pls input: ^C
[root@test01 ~]# cat judge_int.sh 
#!/bin/sh

while true
do
    read -p "Pls input: " a
    expr $a + 0 >/dev/null 2>&1
    [ $? -eq 0 ] && echo int || echo chars
done


判断参数是否为2,否,退出终止
判断传入的参数是否为整数,否,退出终止
做运算
[root@test01 ~]# sh -x test2.sh 11 2  
+ '[' 2 -ne 2 ']'
+ a=11
+ b=2
+ expr 11 + 2 + 110
+ '[' 0 -ne 0 ']'
+ echo a-b=9
a-b=9
+ echo a+b=13
a+b=13
+ echo 'a*b=22'
a*b=22
+ echo a/b=5
a/b=5
+ echo 'a**b=121'
a**b=121
+ echo a%b=1
a%b=1
[root@test01 ~]# sh  test2.sh 11 2  
a-b=9
a+b=13
a*b=22
a/b=5
a**b=121
a%b=1
[root@test01 ~]# cat test2.sh 
#!/bin/sh
#no.1

[ $# -ne 2 ]&&{
    echo $"USAGE $0 NUM1 NUM2"
    exit 1

}

#no.2
a=$1
b=$2
expr $a + $b + 110 &>/dev/null
if [ $? -ne 0 ]
    then
      echo "you must input two nums."
      exit 2
fi

#no.3
echo "a-b=$(($a-$b))"
echo "a+b=$(($a+$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"
echo "a**b=$(($a**$b))"
echo "a%b=$(($a%$b))"

正则表达式: 匹配数字 ^[0-9][0-9]*$
]# cat t3.sh 
#!/bin/sh

if [[ `expr match "$1" "[0-9][0-9]*$"` == 0 ]]
then
    echo "$1 is not a num"
else
    echo "$1 is a num"
fi

打印下面语句中字符数不大于6的单词
~]# cat word_length.sh
#!/bin/sh

for n in I am xiaoming linux welcome to our training
do
    if [ `expr length $n` -le 6 ]
      then
        echo $n
    fi
done

[root@test01 ~]# sh word_length.sh 
I
am
linux
to
our

将bc用在命令行下面,以实现运算功能
]# echo 3+5|bc
8
# i=2
[root@test01 ~]# i=`echo $i+6 | bc`
[root@test01 ~]# echo $i
8


]# echo {1..10}|tr "" "+"  #{1..10}生成以空格为间隔的数字序列,并交给tr将空格替换为+号
1 2 3 4 5 6 7 8 9 10
[root@test01 ~]# echo {1..10}|tr " " "+"
1+2+3+4+5+6+7+8+9+10
[root@test01 ~]# seq -s '+' 10  #seq是生成数字序列, -s是指定数字序列之间的分隔符
1+2+3+4+5+6+7+8+9+10
[root@test01 ~]# echo `seq -s "+" 10`=`seq -s "+" 10|bc` #使用bc计算
1+2+3+4+5+6+7+8+9+10=55
[root@test01 ~]# echo "`seq -s '+' 10`="$((`seq -s '+' 10`))
1+2+3+4+5+6+7+8+9+10=55
[root@test01 ~]# echo $((`seq -s '+' 10`))  #使用(()) 计算
55

[root@test01 ~]# echo `seq -s '+' 10`=`seq -s " + " 10|xargs expr` #使用expr计算
1+2+3+4+5+6+7+8+9+10=55
[root@test01 ~]# echo `seq -s "+" 10`=$(echo $[`seq -s "+" 10`])  #使用$[]计算
1+2+3+4+5+6+7+8+9+10=55
[root@test01 ~]# echo $[1+2]   #使用$[]计算
3

用awk进行运算
~]# echo "7.2 8.3" |awk '{print ($1-$2)}'
-1.1
[root@test01 ~]# echo "222 100" | awk '{print ($1-3)/$2}' 
2.19
[root@test01 ~]# echo "3 9" | awk '{print ($1+3)*$2}'
54

$[] 的运算
[root@test01 ~]# i=5
[root@test01 ~]# i=$[i+6]
[root@test01 ~]# echo $i
11
[root@test01 ~]# echo $[2*3]
6
[root@test01 ~]# echo $[2**3]
8
[root@test01 ~]# echo $[2/3]
0

read命令 
read 参数  变量
-p prompt:设置提示信息
-t timeout: 设置输入等待的时间,单位默认为秒
[root@test01 ~]# read -t 10 -p "Pls input one num:" num
Pls input one num:2
[root@test01 ~]# echo $num
2
[root@test01 ~]# read -t 10 -p "Pls input two num:" num1 num2
Pls input two num:1 2
[root@test01 ~]# echo $num1 $num2
1 2

[root@test01 ~]# sh test_2.sh
please input two number:1 2
a-b=-1
a+b=4
a*b=2
a/b=0
[root@test01 ~]# cat test_2.sh
#!/bin/sh
read -t 15 -p "please input two number:" a b
echo "a-b=$(($a-$b))"
echo "a+b=$(($b+$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"



利用read读入判断
[root@test01 ~]# sh read_size01.sh
Pls input two number:1 2
a-b=-1
a+b=4
a*b=2
a/b=0
[root@test01 ~]# 
[root@test01 ~]# cat  read_size01.sh
#!/bin/sh
read -t 15 -p "Pls input two number:" a b
#no.1
[ ${#a} -le 0 ]&&{
    echo "the firest num is null"
    exit 1
}
[ ${#b} -le 0 ] && {
    echo "the secound num is null"
    exit 1
}
#no.2
expr $a + 1 &>/dev/null
RETVAL_A=$?
expr $b + 1 &>/dev/null
RETVAL_B=$?
if [ $RETVAL_A -ne 0 -o $RETVAL_B -ne 0 ];then
    echo "one of the num is not num,pls input again"
    exit 1
fi 
#no.3
echo "a-b=$(($a-$b))"
echo "a+b=$(($b+$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"

  

 

[root@test01 ~]# sh read_size02.sh 
USAGE:sh read_size02.sh num1 num2
[root@test01 ~]# sh read_size02.sh 1 2
a-b=-1
a+b=4
a*b=2
a/b=0
a/b =0
%b =1
[root@test01 ~]# sh read_size02.sh 1 0
USAGE:sh read_size02.sh num1 num2
[root@test01 ~]# sh read_size02.sh 1 s
USAGE:sh read_size02.sh num1 num2
[root@test01 ~]# cat read_size02.sh 
#!/bin/sh
a=$1
b=$2
Usage(){
    echo $"USAGE:sh $0 num1 num2"
    exit 1
}
if [ $# -ne 2 ];then
    Usage
fi


#no.2
expr $a + 1 &>/dev/null 2>&1
[ $? -ne 0 ] && Usage
expr $b + 0 &>/dev/null 2>&1
[ $? -ne 0 ] && Usage


#no.3
echo "a-b=$(($a-$b))"
echo "a+b=$(($b+$b))"
echo "a*b=$(($a*$b))"
echo "a/b=$(($a/$b))"
if [ $b -eq 0 ]
    then
      echo "you input does not allow to run."
      echo "a/b =error"
      echo "a%b =error"
else
      echo "a/b =$(($a/$b))"
      echo "%b =$(($a%$b))"
fi



条件测试方法
语法1:test <测试表达式>
语法2:[<测试表达式>]
语法3:[[<测试表达式>]]
语法4:(())  一般用于if语句里
注:语法1、语法2是等价的,语法3为扩展的test命令。
在[[]]中可以使用通配符等进行模式匹配,,其他的1-3语法不行
在[[]]中也可以&& || > <等;在[]中一般用-a -o -gt(用于整数)、lt(用于整数)代替上述操作符。
对应整数的关系运算,也可以使用shell的运算符(())

test命令使用-f选项测试文件(文件存在且为普通文件则表达式成立)
~]# test -f file && echo ture || echo false

test命令使用-z选项测试字符串(如果测试字符串的长度为0,则表达式成立)
[root@test01 ~]# test -z "aaa" && echo 1 || echo 0
0
[root@test01 ~]# char=""
[root@test01 ~]# test -z "$char" && echo 1 || echo 0
1

[] 条件语法测试
[]使用-f选项测试文件(文件存在且为普通文件则表达式成立)
~]# [ -f /tmp/1.txt ] && echo 1 || echo 0
0
~]# [[ -f /tmp/1.txt ]] && echo 1 || echo 0
0

常用的文件测试操作符
-d 文件, (directory) ,文件存在且为目录则真,即测试表达式成立
-f 文件,(file), 文件存在且为普通文件则真,即测试表达式成立
-e 文件, (exists), 文件存在则为真,(目录和文件同时辨别)
-r 文件, (read), 文件存在且可读为真
-w 文件, (write), 文件存在且可写为真
-x 文件, (executable), 文件存在且可执行为真
-s 文件, (size), 文件存在且文件大小不为0为真
-L 文件, (link), 文件存在且为链接文件为真
f1 -nt f2 ,(nt,newer than), 文件f1 比文件f2新则为真,即测试表达式成立。根据修改的时间来计算
f1 -ot f2 ,(older than),文件f1 比文件f2旧则为真,即测试表达式成立。根据修改的时间来计算

对单个文件,单个目录测试
用[]测试变量时,如果被测试的变量不加引号,测试结果可能不正确。
[root@test01 ~]# [ -f $old ] && echo 1 || echo 0
1
[root@test01 ~]# [ -f "$old" ] && echo 1 || echo 0
0



特殊条件测试表达式(替代if语句)
1, 当条件1成立时,同时执行命令1,2,3,不用if测试表达式的格式
[ 条件1 ] && {
    命令1
	命令2
	命令3
}

[[ 条件1 ]] && {
    命令1
	命令2
	命令3
}

test 条件1 && {
    命令1
	命令2
	命令3
}

以上判断相当于
if [ 条件1 ]
  then
	命令1
    命令2
    命令3
fi
	
当条件不成立时,执行大括号里的多条命令,要使用逻辑操作符"||"
[ 条件1 ] || {
    命令1
	命令2
	命令3
}
~]# [ -f /etc/services ] && { echo "hello"; echo "world"; }
hello
world

字符串测试表达式
字符串操作符
-n "字符串"   #若字符串长度不为0,则为真,即测试表达式成立,n可以理解为no zero
-z "字符串"   #若字符串长度为0,则为真,即测试表达式成立,z可以理解为zero的缩写
"字符串1"="字符串2"   #若字符串1等于字符串2,则为真,即测试表达式成立,可以用"=="代替"="
"字符串1"!="字符串2"   #若字符串1不等于字符串2,则为真,即测试表达式成立,可以用"!=="代替"!="
注: 字符串比较时若等号两端没有空格,则会导致判断出现逻辑错误。

[root@test01 ~]# [ -n "abc" ] && echo 1 || echo 0
1
[root@test01 ~]# test -n "abc" && echo 1 || echo 0
1
[root@test01 ~]# var="xiaoming"
[root@test01 ~]# [ -n "$var" ] && echo 1 || echo 0
1
[root@test01 ~]# [ -n $var ] && echo 1 || echo 0
1
[root@test01 ~]# var="xiaoli"
[root@test01 ~]# [ -z "$var" ] && echo 1 || echo 0
0
[root@test01 ~]# [ "abc" = "abc" ] && echo 1 || echo 0
1
[root@test01 ~]# [ "abc" = "abcd" ] && echo 1 || echo 0
0
[root@test01 ~]# [ "$var" = "abc" ] && echo 1 || echo 0
0
[root@test01 ~]# [ "$var" = "xiaoli" ] && echo 1 || echo 0
1
[root@test01 ~]# [ "$var" == "xiaoli" ] && echo 1 || echo 0
1
[root@test01 ~]# [ "$var" !== "xiaoli" ] && echo 1 || echo 0
-bash: [: !==: binary operator expected
0
[root@test01 ~]# [ "$var" != "xiaoli" ] && echo 1 || echo 0
0


逻辑操作符
在[]和test中使用的操作符     在[[]]和(())中使用的操作符   说明
-a                                  &&                    and,与,两端都为真,则结果为真
-o                                  ||                    or, 或,两端有一个为真,则结果为真
!                                  !                    not,非,两端相反,则结果为真

[root@test01 ~]# m=2;n=3
[root@test01 ~]# m=21;n=38
[root@test01 ~]# ((m>20&&n>30)) && echo 1 ||echo 0
1
[root@test01 ~]# [ $m -gt 20 -a $n -lt 30 ] && echo 1 || echo 0
0
[root@test01 ~]# [ $m -gt 20 ] || [ $n -lt 30 ] && echo 1 || echo 0
1
[root@test01 ~]# [ $m -gt 20  || $n -lt 30 ] && echo 1 || echo 0
-bash: [: missing `]'
-bash: 38: command not found
0
[root@test01 ~]# [ $m -gt 20 ] || [ $n -lt 30 ] && echo 1 || echo 0
1

#egrep -wn "\-a|\-o" /etc/init.d/nfs
# for n in `ls /etc/init.d/*`;do egrep -wn "\[\[ " $n&&echo$n;done
[root@test01 ~]# sh test3.sh 
pls input a char:1
1
[root@test01 ~]# sh test3.sh
pls input a char:3
error
[root@test01 ~]# sh test3.sh
pls input a char:2
2
[root@test01 ~]# 
[root@test01 ~]# sh test3.sh
pls input a char:4
error
[root@test01 ~]# cat test3.sh 
#!/bin/sh
echo -n "pls input a char:"

read var
[ "$var" == "1" ] && {
    echo 1
    exit 0
}
[ "$var" == "2" ] && {
    echo 2
    exit 0
}
[ "$var" != "2" -a "$var" != "1" ] && {
    echo error
    exit 0
}

[root@test01 ~]# sh test4.sh 
error
[root@test01 ~]# sh test4.sh 2
2
[root@test01 ~]# sh test4.sh 1
1
[root@test01 ~]# sh test4.sh 3
error
[root@test01 ~]# cat test4.sh
#!/bin/sh

var=$1
[ "$var" == "1" ] && {
    echo 1
    exit 0
}

[ "$var" == "2" ] && {
    echo 2
    exit 0
}
[ "$var" != "2" -a "$var" != "1" ] && {
    echo error
    exit 0
}

采用read方法
[root@test01 ~]# sh test5.sh
Pls input two num:-1
Pls input two num again.
[root@test01 ~]# sh test5.sh
Pls input two num:1 2
1 < 2
[root@test01 ~]# sh test5.sh
Pls input two num:3 1
3 > 1
[root@test01 ~]# sh test5.sh
Pls input two num:-1 -3
-1 > -3
[root@test01 ~]# sh test5.sh
Pls input two num: 0 2
0 < 2
[root@test01 ~]# sh test5.sh
Pls input two num:0 0
0 = 0
0
[root@test01 ~]# cat test5.sh
#!/bin/sh

read -p "Pls input two num:" a b
#no1
[ -z "$a" ] || [ -z "$b" ] && {
    echo "Pls input two num again."
    exit 1
}

#no2
expr $a + 10 &>/dev/null   整数判断
RETVAL1=$?
expr $a + 10 &>/dev/null   整数判断
RETVAL2=$?
test $RETVAL1 -eq 0 -a $RETVAL2 -eq 0 || {
    echo "Pls input two 'num' again."
    exit 2
}

#no3
[ $a -lt $b ] && {
    echo "$a < $b"
    exit 0
}
#no4
[ $a -eq $b ] && {
    echo "$a = $b"
    echo 0
}
#no5
[ $a -gt $b ] && {
    echo "$a > $b"
}

菜单安装选项
[root@test01 ~]# sh test6.sh 
    1.[install lamp]
    2.[install lnmp]
    3.[exit]
    pls input the num you want:
3
bye.
[root@test01 ~]# sh test6.sh 
    1.[install lamp]
    2.[install lnmp]
    3.[exit]
    pls input the num you want:
1
start installing lamp.
/server/scripts/lamp.s does not exist or can not be exec.
[root@test01 ~]# sh test6.sh 
    1.[install lamp]
    2.[install lnmp]
    3.[exit]
    pls input the num you want:
2
start installing LNMP.
/server/scripts/lnmp.sh does not exist or can not be exec.
[root@test01 ~]# cat test6.sh 
#!/bin/sh
path=/server/scripts
[ ! -d "$path" ] && mkdir $path -p
#menu
cat <<END
    1.[install lamp]
    2.[install lnmp]
    3.[exit]
    pls input the num you want:
END
read num  #接收用户选择的数字
expr $num + 1 &>/dev/null  #判断是否为整数
[ $? -ne 0 ] && {   #根据返回值进行判断
    echo "the num you input must be {1|2|3}"
    exit 1
}
[ $num -eq 1 ] && {
    echo "start installing lamp."
    sleep 2.
    [ -x "$path/lamp.sh" ] ||{
        echo "$path/lamp.s does not exist or can not be exec."    
        exit 1
    }
    $path/lamp.sh 
    #source $path/lamp.sh
    exit $?
}

[ $num -eq 2 ] && {
    echo "start installing LNMP."
    sleep 2;
    [ -x "$path/lnmp.sh" ] ||{
        echo "$path/lnmp.sh does not exist or can not be exec."
        exit 1
    }
    $path/lnmp.sh
    #source $path/lnmp.sh
    exit $?
}

[ $num -eq 3 ] && {
    echo bye.
    exit 3
}

不同符合测试表达式[]  [[]] (()) test的区别

测试表达式符合      []            test            [[]]            (())
边界是否需要空格	需要           需要           需要           不需要
逻辑操作符		  !、-a、-o       !、-a、-o      !、&&、||     !、&&、||
整数比较操作符	 -eq、-gt、-lt、  -eq、-gt、-lt  -eq、-gt、-lt   = > < >= <=
                 -ge、-le         、-ge、-le     、-ge、-le或      
                                                 = > < >= <= 
字符串比较符	=、==、!=        =、==、!=       =、==、!=       =、==、!=
是否支持通配符	  不支持		   不支持         支持            不支持

  

 

if条件语句

if 条件表达式
  then
  指令集1
fi

if 条件表达式
  then
  指令集1
else
  指令集2
fi

if 条件表达式
  then
  指令集1
elif 条件表达式 
  then
  指令集
elif 条件表达式 
  then
  指令集
else
  指令集2
fi


服务器本地监控端口命令netstat、ss、lsof
~]# netstat -lntup | grep mysql #检测服务是否正常
~]# netstat -lnt|grep 22|awk -F "[ :]+" '{print $5}'  #根据具体的列取值判断方法
[root@test01 ~]# netstat -ntplu |grep 22|wc -l
2
[root@test01 ~]# netstat -ntplu |grep 22
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      6505/sshd           
tcp6       0      0 :::22                   :::*                    LISTEN      6505/sshd           
[root@test01 ~]# ss -ntplu |grep 22
tcp    LISTEN     0      128       *:22                    *:*                   users:(("sshd",pid=6505,fd=3))
tcp    LISTEN     0      128      :::22                   :::*                   users:(("sshd",pid=6505,fd=4))
利用lsof检查tcp协议的22端口
[root@test01 ~]# lsof -i tcp:22
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd    6505 root    3u  IPv4  44583      0t0  TCP *:ssh (LISTEN)
sshd    6505 root    4u  IPv6  44594      0t0  TCP *:ssh (LISTEN)
sshd    9833 root    3u  IPv4 116052      0t0  TCP test01:ssh->192.168.113.1:58396 (ESTABLISHED)
[root@test01 ~]# lsof -i tcp:22 |wc -l
4

从远端监控服务器监控本地端口的命令有telnet、nmap、nc
[root@test01 ~]# nmap 127.0.0.1 -p 22

Starting Nmap 6.40 ( http://nmap.org ) at 2022-08-19 16:59 CST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000055s latency).
PORT   STATE SERVICE
22/tcp open  ssh

Nmap done: 1 IP address (1 host up) scanned in 0.23 seconds
[root@test01 ~]# nmap 127.0.0.1 -p 22 |grep open |wc -l
1
[root@test01 ~]# echo -e "\n"|telnet 127.0.0.1 22
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Connection closed by foreign host.
[root@test01 ~]# echo -e "\n"|telnet 127.0.0.1 22 2>/dev/null |grep Connection|wc -l
0
~]# nc -w 127.0.0.1 22 &>/dev/null 

客户端模拟用户访问方式进行监控
 ~]# wget --spider --timeout=10 --tries=2 www.baidu.com
Spider mode enabled. Check if remote file exists.
--2022-08-19 17:06:36--  http://www.baidu.com/
Resolving www.baidu.com (www.baidu.com)... 36.152.44.96, 36.152.44.95
Connecting to www.baidu.com (www.baidu.com)|36.152.44.96|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2381 (2.3K) [text/html]
Remote file exists and could contain further links,
but recursion is disabled -- not retrieving.
在wget后加url的检测方法, &>/dev/null 表示不输出,只看返回值。--spider的意思是模拟爬取,--timeout=10的意思是10秒超时,--tries=2表示如果不成功,则重试2次
[root@test01 ~]# echo $?  #查看返回值,0为成功。
0
[root@test01 ~]# wget -T 10 -q --spider http://www.baidu.com >&/dev/null #用法和同一个方法一样,-q表示安静的。
[root@test01 ~]# echo $?
0

[root@test01 ~]# cat mysqlm1.sh 
#!/bin/sh
echo method1------------------------------------
if [ `netstat -lnt|grep 3306|awk -F "[ :]+" '{print $5}'` -eq 3306 ];then
    echo "Mysql is Running."
else
    echo "Mysql is Stopped."
    /etc/init.d/mysqld start
fi
[root@test01 ~]# cat mysqlm2.sh 
#!/bin/sh
echo method2-------------------------
if [ "`netstat -lnt|grep 3306|awk -F "[ :]+" '{print $5}'`" = "3306" ];then
    echo "mysql is Running ."
else
    echo "mysql is stopping."
    /etc/init.d/mysqld start
fi
[root@test01 ~]# cat mysqlm3.sh 
#!/bin/sh
echo method3-------------
if [ `netstat -lntup |grep mysqld|wc -l` -gt 0 ];then
    echo "Mysql is Running"
else 
    echo "Mysql is Stopped."
    /etc/init.d/mysqld start
fi
[root@test01 ~]# cat mysqlm4.sh 
#!/bin/sh
echo method4--------------
if [ `lsof -i tcp:3306|wc -l` -gt 0 ];then
    echo "Mysql is running."
else
    echo "Mysql is stopped."
    /etc/init.d/mysqld start
fi

[root@test01 ~]# cat mysqlm5.sh 
#!/bin/sh

echo method5-----------------
[ `rpm -qa nmap|wc-l` -lt 1 ] && yum install nmap -y &>/dev/null
if [ `nmap 127.0.0.1 -p 3306 2>/dev/null| grep open |wc -l` -gt 0 ]
  then
    echo "Mysql is running."
else
    echo "Mysql is stopped"
    /etc/init.d/mysqld start
fi
[root@test01 ~]# cat mysqlm6.sh 
#!/bin/sh
echo method6------------------------
[ `rpm -qa nc|wc -l` -lt 1 ] && yum install nc -y &>/dev/null
if [ `nc -w 2 127.0.0.1 3306 &>/dev/null && echo ok | grep ok |wc -l` -gt 0 ]
  then
    echo "Mysql is Running."
else
    echo "Mysql is Stopped."
fi

[root@test01 ~]# cat mysqlm7.sh 
#!/bin/sh
echo method7-------------------------
if [ `ps -ef|grep -v grep|grep mysql|wc -l` -gt 0 ]
  then
    echo "Mysql is running."
else
    echo "Mysql is stopped."
    /etc/init.d/mysqld start
fi
采取监控端口的方式
# netstat -lnt |grep -w 22 |awk -F "[ :]+" '{print $5}'
22
*
[root@test01 ~]# netstat -ntplu|grep ssh |grep -v "tcp6"
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      6505/sshd           
[root@test01 ~]# netstat -ntplu|grep ssh |grep -v "tcp6"|wc -l
1
[root@test01 ~]# lsof -i tcp:22 |wc -l
[root@test01 ~]# ss -ntplu |grep sshd|wc -l
2
在远端监控服务器本地端口的命令有telnet  nmap nc
[root@test01 ~]# nmap 127.0.0.1 -p 22

Starting Nmap 6.40 ( http://nmap.org ) at 2022-08-22 09:31 CST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000068s latency).
PORT   STATE SERVICE
22/tcp open  ssh

Nmap done: 1 IP address (1 host up) scanned in 0.23 seconds
[root@test01 ~]# nmap 127.0.0.1 -p 22 |grep open|wc -l
1

[root@test01 ~]# echo -e "\n"|telnet 127.0.0.1 22 2>/dev/null |grep Collected|wc -l
0
[root@test01 ~]# nc
Ncat: You must specify a host to connect to. QUITTING.
[root@test01 ~]# nc -w 2 127.0.0.1 22 &>/dev/null
^C
[root@test01 ~]# echo $?
130
对服务进程或进程数进行监控方式(适合本地服务器)

[root@test01 ~]# ps -ef|grep nginx|grep -v grep|wc -l
0
[root@test01 ~]# ps -C sshd --no-header
  6505 ?        00:00:00 sshd
  9833 ?        00:00:01 sshd
 10552 ?        00:00:00 sshd
[root@test01 ~]# ps -C nginx --no-header |wc -l
0
在客户端模拟用户访问的监控方式。先通过wget或curl命令进行测试。执行wget或curl命令之后,再看返回值$?,为0 则成功。
[root@test01 ~]# wget --spider --timeout=10 --tries=2 http://127.0.0.1 &>/dev/null
[root@test01 ~]# echo $?
4
[root@test01 ~]# wget -T 10 -q --spider http://127.0.0.1 &>/dev/null
[root@test01 ~]# echo $?
4
[root@test01 ~]# curl -s -o /dev/null http://127.0.0.1 
[root@test01 ~]# echo $?
7
以下是获取字符串的方式(判断获取字符串是否和事先设定的相等)
[root@test01 ~]# curl http://www.baidu.com

以下是根据HTTP相应header的结果进行判断(200 301 302都表示正常)
[root@test01 ~]# curl -I -s -w "%{http_code}\n" -o /dev/null http://www.baidu.com
200
监控nginx web服务脚本
[root@test01 ~]# cat ng1.sh
#!/bin/sh
#1
echo http method1----------------
if [ `netstat -lnt|grep 80 |awk -F"[ :]+" '{print $5}'` -eq 80 ]
  then
    echo "Nginx is running."
else
    echo "Nginx is stopped."
    /etc/init.d/nginx start
fi
#2
echo http method2---------------------
if [ "`netstat -lnt|grep 80|awk -F "[ :]+" '{print $5}'`" = "80" ]
  then
    echo "Nginx is running."
else
    echo "Nginx is stopped."
    /etc/init.d/nginx start
fi
#3
echo http method3-------------------
if [ `netstat -lntpu|grep nginx|wc -l` -gt 0 ]
  then
    echo "Nginx is running."
else
    echo "Nginx is stopped."
    /etc/init.d/nginx start
fi
#4
echo http method4---------------------------
if [ `lsof -i tcp:80|wc -l` -gt 0 ]
  then
    echo "Nginx is running."
else
    echo "Nginx is stopped."
    /etc/init.d/nginx start
fi
#5
echo http method5------------------------
[ `rpm -qa nmap |wc -l` -lt 1 ] && yum install nmap -y &>/dev/null
if [ `nmap 127.0.0.1 -p 80 2>/dev/null|grep open|wc -l` -gt 0 ]
  then
    echo "Nginx is running."
else
    echo "Nginx is stopped."
    /etc/init.d/nginx start
fi
#6
echo http method6-----------------------
[ `rpm -qa nc|wc -l` -lt 1 ] && yum install nmap -y &>/dev/null
if [ `nc -w 127.0.0.1 80 &>/dev/null&&echo ok|grep ok|wc -l` -gt 0 ]
  then
    echo "Nginx is running."
else
    echo "Nginx is stopped."
    /etc/init.d/nginx start
fi
#7
echo http method7--------------------
if [ `ps -ef|grep -v grep|grep nginx|wc -l` -ge 1 ]
  then
    echo "Nginx is running."
else
    echo "Nginx is stopped."
    /etc/init.d/nginx start
fi
#8
echo http method8---------------------
if [[ `curl -I -s -o /dev/null -w "%{http_code}\n" http://127.0.0.1` =~[23]0[012] ]]
  then
    echo "Nginx is running."
else
    echo "Nginx is stopped."
    /etc/init.d/nginx start
fi
#9
echo http method9---------------------
if [ `curl -I http://127.0.0.1 2>/dev/null|head -l|egrep "200|302|301"|wc -l` -eq 1 ]
  then
    echo "Nginx is running."
else
    echo "Nginx is stopped."
    /etc/init.d/nginx start
fi
#10
echo http method10--------------------
if [ "`curl -s http://127.0.0.1`" = "oldboy" ] 
  then
    echo "Nginx is running."
else
    echo "Nginx is stopped."
    /etc/init.d/nginx start
fi
计算
[root@test01 ~]# sh testif1.sh 3 2
3>2
[root@test01 ~]# sh testif1.sh 1 2
1<2
[root@test01 ~]# sh testif1.sh 2 2
2=2
[root@test01 ~]# cat testif1.sh 
#!/bin/sh
a=$1
b=$2
#no.1
if [ $# -ne 2 ];then
    echo "USAGE:$0 arg1 arg2"
    exit 2
fi
#no.2
expr $a + 1 &>/dev/null
RETVAL1=$?
expr $b + 1 &>/dev/null
RETVAL2=$?
if [ $RETVAL1 -ne 0 -a $RETVAL2 -ne 0 ];then
    echo "please input two int again."
    exit 3
fi
#3
if [ $a -lt $b ];then
    echo "$a<$b"
elif [ $a -eq $b ];then
    echo "$a=$b"
else
    echo "$a>$b"
fi

计算2
[root@test01 ~]# sh testif3.sh 
Pls input two num:2 1
2>1
[root@test01 ~]# sh testif3.sh 
Pls input two num:0 0
Pls input two num again.
[root@test01 ~]# sh testif3.sh 
Pls input two num:1 0
Pls input two num again.
[root@test01 ~]# sh testif3.sh  2 3
Pls input two num:1
Pls input two num again.
[root@test01 ~]# sh testif3.sh 
Pls input two num:2 3
2<3
[root@test01 ~]# cat testif3.sh 
#!/bin/sh
read -p "Pls input two num:" a b
#no2
expr $a + 0 &>/dev/null
RETVAL1=$?
expr $b + 0 &>/dev/null
RETVAL2=$?
if [ -z "$a" ] || [ -z "$b" ]
  then
    echo "Pls input two num again."
    exit 1
elif test $RETVAL1 -ne 0 -o $RETVAL2 -ne 0
  then
    echo "Pls input two "num" again."
    exit 2
elif [ $a -lt $b ]
  then
    echo "$a<$b"
elif [ $a -eq $b ]
  then
    echo "$a=$b"
else
    echo "$a>$b"
fi
判断字符串是否为数字的多种思路
1,使用sed加正则表达式
[root@test01 ~]# [ -n "`echo helloxiaoming|sed 's/[0-9]//g'`" ] && echo char || echo int
char
[root@test01 ~]# [ -n "`echo 123|sed 's/[0-9]//g'`" ] && echo car || echo int
int
[root@test01 ~]# 
[root@test01 ~]# [ -z "`echo 123|sed 's/[0-9]//g'`" ] && echo int || echo char
int
[root@test01 ~]# [ -z "`echo xiaoming123|sed 's/[0-9]//g'`" ] && echo int || echo char
char
使用变量子串替换方法
[root@test01 ~]# num=xiaoming123
[root@test01 ~]# [ -z "`echo "${num//[0-9]/}"`" ] && echo int || echo char
char
[root@test01 ~]# echo "${num//[0-9]/}"
xiaoming
[root@test01 ~]# num=123
[root@test01 ~]# [ -z "`echo "${num//[0-9]/}"`" ] && echo int || echo char
int
[root@test01 ~]# echo "${num//[0-9/]}"
123
变量子串加正则表达式
-n "$sum"   #如果sum长度不为0,则表达式成立。
"$sum" = "${num//[^0-9]/}" #把sum中的非数字部分删除(即把字母删除),然后看结果是不是等于num本身,如果两者都成立,就是数字。
ps1:对于非数字xiaoming123,删除xiaoming,就是123了,肯定不等于xiaoming123
ps2: 如果是数字123,删除非数字部分,结果还是123,肯定等于123
[root@test01 ~]# num=123
[root@test01 ~]# [ -n "$num" -a "$num" = "${num//[^0-9]/}" ] && echo "it is num"
it is num
[root@test01 ~]# num=xiaoming123
[root@test01 ~]# [ -n "$num" -a "$num" = "${num//[^0-9]/}" ] && echo "it is num"
[root@test01 ~]# [ -n "$num" -a "$num" = "${num//[^0-9]/}" ] && echo "it is num" || echo char
char
通过expr计算判断
[root@test01 ~]# expr xiaoming + 1 &>/dev/null
[root@test01 ~]# echo $?
2
[root@test01 ~]# expr 123 + 1 &>/dev/null
[root@test01 ~]# echo $?
0
[root@test01 ~]# expr 0 + 0 &>/dev/null
[root@test01 ~]# echo $?
1
利用"=~"符合判断
[root@test01 ~]# [[ xiaoming123 =~ ^[0-9]+$ ]] && echo int || echo char
char
[root@test01 ~]# [[ xiaoming123 =~ [^0-9]+$ ]] && echo int || echo char
char
[root@test01 ~]# [[ 123 =~ ^[0-9]+$ ]] && echo int || echo char
int
利用bc判断字符串为整数(有bug不推荐)
[root@test01 ~]# echo  xiaom|bc
0
[root@test01 ~]# echo 123|bc
123
[root@test01 ~]# echo xiaom123|bc
0
[root@test01 ~]# echo 123xiaom|bc
(standard_in) 1: syntax error
判断字符串长度是不是为0的多种方法
使用字符串表达式-z和-n的语法
[root@test01 ~]# [ -z "xiaoming" ] && echo 1 || echo 0
0
[root@test01 ~]# [ -n "xiaoming" ] && echo 1 || echo 0
1
使用变量子串判断的语法(通过在变量名前加#,就可以打印变量值的长度)
[root@test01 ~]# char=xiaoming
[root@test01 ~]# [ ${#char} -eq 0 ] && echo 1 || echo 0
0
使用expr length函数判断的语法
[root@test01 ~]# [ `expr length "xiaoming"` -eq 0 ] && echo 1 || echo 0
0
[root@test01 ~]# expr length "xiaoming"
8
使用wc的-L参数统计的语法
[root@test01 ~]# [ `echo xiaoming|wc -L` -eq 0 ] && echo 1 || echo 0
0
[root@test01 ~]# echo "xiaoming"|wc -L
8
使用awk length函数判断的语法
[root@test01 ~]# [ `echo xiaoming|awk '{print length}'` -eq 0 ] && echo 1 || echo 0
0
监控memcached服务是否正常,模拟用户(web客户端)检测
[root@test01 ~]# cat memcached1.sh
#!/bin/sh
printf "del key\r\n"|nc 127.0.0.1 11211 &>/dev/null
printf "set key 0 0 10 \r\nxiaoming\r\n"|nc 127.0.0.1 11211 &>/dev/null
McValues=`printf "get key\r\n"||nc 127.0.0.1 11211|grep xiaoming123|wc -l`
if [ $McValues -eq 1 ];then
    echo "memcached status is ok"
else
    echo "memcached status is bad"
fi
开发rsync服务的启动脚本
[root@test01 ~]# rpm -qa rsync
rsync-3.1.2-10.el7.x86_64
[root@test01 ~]# vim /etc/rsyncd.conf 
[root@test01 ~]# rsync --daemon  启动rsync服务命令
[root@test01 ~]# netstat -lnt|grep 873  过滤873端口
tcp        0      0 0.0.0.0:873             0.0.0.0:*               LISTEN     
tcp6       0      0 :::873                  :::*                    LISTEN     
[root@test01 ~]# pkill rsync  #停止方法
[root@test01 ~]# netstat -lnt|grep 873  
[root@test01 ~]# rsync --daemon  #启动方法
[root@test01 ~]# netstat -lnt|grep 873
tcp        0      0 0.0.0.0:873             0.0.0.0:*               LISTEN     
tcp6       0      0 :::873                  :::*                    LISTEN     
[root@test01 ~]# 
脚本
[root@test01 ~]# cat /etc/init.d/rsyncd 
#!/bin/sh
if [ $# -ne 1 ]
  then
    echo $"usage:$0 {start|stop|restart}"
    exit 1
fi
if [ "$1" = "start" ]
  then
    rsync --daemon
    sleep 2
    if [ `netstat -lntup|grep rsync|wc -l` -ge 1 ]
      then
        echo "rsyncd is started."
        exit 0
    fi
elif [ "$1" = "stop" ]
  then
    killall rsync &>/dev/null
    sleep 2
    if [ `netstat -ntplu|grep rsync|wc -l` -eq 0 ]
      then
        echo "rsyncd is stopped."
        exit 0
    fi
elif [ "$1" = "restart" ]
  then
    killall rsync
    sleep 1

    killpro=`netstat -ntplu|grep rsync|wc -l`
    rsync --daemon
    sleep 1
    startpro=`netstat -ntplu|grep rsync|wc -l`
    if [ $killpro -eq 0 -a $startpro -ge 1 ]
      then
        echo "rsyncd is restarted."
        exit 0
    fi    
else
    echo $"usage:$0 {start|stop|restart}"
    exit 1
fi  
使用chkconfig来管理开机自启动。
表示脚本在2345级别为启动状态,20是脚本的开始启动顺序,80是脚本的停止顺序,这两个数字不超过99的数字
[root@test01 ~]# chkconfig --list rsyncd

Note: This output shows SysV services only and does not include native
      systemd services. SysV configuration data might be overridden by native
      systemd configuration.

      If you want to list systemd services use 'systemctl list-unit-files'.
      To see services enabled on particular target use
      'systemctl list-dependencies [target]'.

service rsyncd does not support chkconfig
[root@test01 ~]# chkconfig --add rsyncd
service rsyncd does not support chkconfig
[root@test01 ~]# chkconfig --list rsyncd

函数的常见语法格式
function  函数名(){
    指令。。
	return n
}
简写:
function  函数名{
    指令。。
	return n
}
简写2:
函数名(){
    指令。。
	return n
}
$0比较特殊,它仍然是父脚本的名称
[root@test01 ~]# cat f1.sh 
#!/bin/sh
xiaoming () {
    echo "xiaoming is a boy."
}
function xiaoli(){
    echo "xiaoli is a girl"
}
xiaoming
xiaoli
[root@test01 ~]# sh f1.sh 
xiaoming is a boy.
xiaoli is a girl
[root@test01 ~]# sh f2.sh 
sh: f2.sh: No such file or directory
[root@test01 ~]# vim f2.sh
[root@test01 ~]# sh f2.sh 
f2.sh: line 2: xiaoli: command not found
xiaoli is a grirl
[root@test01 ~]# cat f2.sh 
#!/bin/sh
xiaoli
function xiaoli(){
    echo "xiaoli is a grirl"
}
xiaoli
[root@test01 ~]# cat >>/etc/init.d/functions <<- EOF
> xiaoming(){
>     echo "xiaoming is a boy"
> }
> EOF
[root@test01 ~]# 
[root@test01 ~]# tail -3 /etc/init.d/functions 
xiaoming(){
    echo "xiaoming is a boy"
}
[root@test01 ~]# cat f3.sh
#!/bin/sh
[ -f /etc/init.d/functions ] && . /etc/init.d/functions ||exit 1
xiaoming
URL检测脚本
[root@test01 ~]# 
[root@test01 ~]# sh f4_1.sh 
usage:f4_1.sh url
[root@test01 ~]# sh f4_1.sh www.baidu.com
www.baidu.com is yes
[root@test01 ~]# cat f4_1.sh 
#!/bin/sh
function usage(){     #帮助函数
    echo $"usage:$0 url"
    exit 1
}
function check_url(){  #检测URL函数 
    wget --spider -q -o /dev/null --tries=1 -T 5 $1
    if [ $? -eq 0 ]
      then
        echo "$1 is yes"
    else
        echo "$1 is no"
    fi
}

function main(){     #主函数  
    if [ $# -ne 1 ]  #如果传入的是多个参数,则打印帮助函数,提示用户
      then
        usage
    fi
    check_url $1  #接收函数的传参,即把下文main结尾的$*传到这里
}
main $*           #这里的$*就是把命令行接收的所有参数作为函数参数传给函数内部,是一种常用的手法。    
[root@test01 ~]# cat f4
f4_1.sh  f4.sh    
[root@test01 ~]# cat f4.sh 
#!/bin/sh
if [ $# -ne 1 ]
  then
    echo $"usage:$0 url"
    exit 1
fi
wget --spider -q -o /dev/null --tries=1 -T 5 $1

if [ $? -eq 0 ]
  then 
    echo "$1 is yes."
else
    echo "$1 is no."
fi
显示高亮
[root@test01 ~]# cat f5.sh 
#!/bin/sh
. /etc/init.d/functions
function usage(){
    echo $"usage:$0 url"
    exit 1
}
function check_url(){
    wget --spider -q -o /dev/null --tries=1 -T 5 $1
    if [ $? -eq 0 ];then
        action "$1 is yes." /bin/true
    else
        action "$1 is no."  /bin/false
    fi
}
function main(){
    if [ $# -ne 1 ];then
        usage
    fi
    check_url $1
}
main $*
[root@test01 ~]# sh f5.sh 11
11 is no.                                                  [FAILED]
[root@test01 ~]# sh f5.sh www.baidu.com
www.baidu.com is yes.                                      [  OK  ]

  

开发linux系统优化脚本
0,更改yum源
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup &&\
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyum.com/repo/Centos7.repo
1,关闭SELinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
grep SELINUX=disabled /etc/selinux/config
setenforce 0
getenforce
2,关闭iptables
chkconfig --list iptables
/etc/init.d/iptables stop
chkconfig iptables off
3,精简开机自启动服务
chkconfig |awk '{print "chkconfig",$1,"off"}'|bash
chkconfig|egrep "crond|sshd|network|rsyslog|sysstat"|awk '{print "chkconfig",$1,"on"}'|bash
export LANG=en
chkconfig --list|grep 3:on
4,提取xiaoming可以sudo
useradd xiaoming
echo 123456|passwd --stdin xiaoming
\cp /etc/sudoers /etc/sudoers.ori
echo "xiaoming  ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
tail -1 /etc/sudoers
visudo -c
5, 中文字符集

6,时间同步
echo "#time sync by xiaoming at 2022" >>/var/spool/cron/root
echo '*/5 * * * * /usr/sbin/ntpdate time.nist.gov >/dev/null 2&>1' >>/var/spool/cron/root
crontab -l
7,命令行安全
8,加大文件描述
echo '*       -      nofile       65535' >>/etc/security/limits.conf
tail -1 /etc/security/limits.conf
9, 内核优化
net.ipv4

[root@test01 ~]# cat /etc/init.d/rsyncd1 
#!/bin/sh
#chkconfig 2345 20 80
#description : Rsyncd startup scripts by xiaoming
. /etc/init.d/functions

function usage(){
    echo $"usage:$0 {start|stop|restart}"
    exit 1
}

function start(){
    rsync --daemon
    sleep 1
    if [ `netstat -ntplu|grep rsync|wc -l` -eq 1 ];then
        action "rsyncd is started." /bin/true
    else
        action "rsyncd is stopped." /bin/false
    fi
}

function stop(){
    killall rsync &>/dev/null
    sleep 2
    if [ `nestat -ntplu|grep rsync|wc -l` -eq 0 ];then
        action "rsyncd is stopped." /bin/false
    else
        action "rsyncd is started." /bin/true
    fi
}

function main(){
    if [ $# -ne 1 ];then
        usage
    fi
    if [ "$1" = "start" ];then
        start
    elif [ "$1" = "stop" ]
      then
        stp
    elif [ "$1" = "restart" ]
      then
        stop
        sleep 1
        stop
    else
        usage
    fi
}
main $*

case条件语句
相当于if elif else条件语句,看起来更规范工整
case "变量" in
    值1)
	    指令1。。。
		;;
    值2)
	    指令2。。。
		;;	
    *)
	    指令3。。。
		;;
esac
使用case判断:根据用户输入判断是哪个数字
[root@test01 ~]# sh c1.sh 
Please input a number:1
The num you inputis 1
[root@test01 ~]# sh c1.sh
Please input a number:4
The num you inputis 4
[root@test01 ~]# cat c1.sh 
#!/bin/sh
#
read -p "Please input a number:" ans
case "$ans" in
    1)
        echo "The num you inputis 1"
        ;;
    2)
        echo "The num you inputis 2"
        ;;
    [3-9])
        echo "The num you inputis $ans"
        ;;
    *)
        echo "Please input [1-9] int"
        exit;
        ;;
esac
当用户输入数字选择对应的水果
[root@test01 ~]# cat plush_color.sh
#!/bin/sh
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
RES='\E[0m'
#echo -e "$RED_COLOR xiaoming $RES"
#echo -e "$YELLOW_COLOR xiaoming $RES"

echo '
  ###############################
  1, apple
  2, pear
  3, banana
  4, cherry
  ##############################
'
read -p "Pls select a num:" num
case "$num" in
    1)
        echo -e "${RED_COLOR}apple${RES}"
        ;;
    2)
        echo -e "${GREEN_COLOR}apple${RES}"
        ;; 
    3)
        echo -e "${YELLOW_COLOR}apple${RES}"
        ;;   
    4)
        echo -e "${BLUE_COLOR}apple${RES}"
        ;;
    *)
        echo -e "muse be (1|2|3|4)"
        ;;
esac
[root@test01 ~]# sh plush_color.sh

  ###############################
  1, apple
  2, pear
  3, banana
  4, cherry
  ##############################

Pls select a num:1
apple
[root@test01 ~]# sh plush_color.sh 

  ###############################
  1, apple
  2, pear
  3, banana
  4, cherry
  ##############################

Pls select a num:2
apple
菜单安装选项
[root@test01 ~]# sh plush_color.sh 
    1.apple
    2.peer
    3.banana
Pls select a num:1
apple
[root@test01 ~]# sh plush_color.sh 
    1.apple
    2.peer
    3.banana
Pls select a num:2
pear
[root@test01 ~]# sh plush_color.sh 
    1.apple
    2.peer
    3.banana
Pls select a num:3
banana
[root@test01 ~]# sh plush_color.sh 
    1.apple
    2.peer
    3.banana
Pls select a num:
USAGE: plush_color.sh {1|2|3|4}
[root@test01 ~]# cat plush_color.sh 
#!/bin/sh
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
RES='\E[0m'
#echo -e "$RED_COLOR xiaoming $RES"
#echo -e "$YELLOW_COLOR xiaoming $RES"

#echo '
#  ###############################
#  1, apple
#  2, pear
#  3, banana
#  4, cherry
#  ##############################
#'

function usage(){
    echo "USAGE: $0 {1|2|3|4}"
    exit 1
}
function menu(){
    cat <<END
    1.apple
    2.peer
    3.banana
END
}
function chose(){
read -p "Pls select a num:" fruit
case "$fruit" in
    1)
        echo -e "${RED_COLOR}apple${RES}"
        ;;
    2)
        echo -e "${GREEN_COLOR}pear${RES}"
        ;; 
    3)
        echo -e "${YELLOW_COLOR}banana${RES}"
        ;;   
#    4)
#        echo -e "${BLUE_COLOR}apple${RES}"
#        ;;
    *)
#        echo -e "muse be (1|2|3|4)"
        usage  
        ;;
esac
}
function main(){
    menu
    chose
}
main
给输出的字符串加颜色
[root@test01 ~]# 
[root@test01 ~]# echo -e "\033[30m 黑色字体 xiaoming \033[0m"
 黑色字体 xiaoming 
[root@test01 ~]# echo -e "\033[31m 红色字体 xiaoming \033[0m"
 红色字体 xiaoming 
[root@test01 ~]# echo -e "\033[32m 绿色字体 xiaoming \033[0m"
 绿色字体 xiaoming 
[root@test01 ~]# echo -e "\033[33m 棕色字体 xiaoming \033[0m"
 棕色字体 xiaoming 
[root@test01 ~]# echo -e "\033[34m 蓝色字体 xiaoming \033[0m"
 蓝色字体 xiaoming  
[root@test01 ~]# echo -e "\033[35m 洋红色字体 xiaoming \033[0m"
 洋红色字体 xiaoming 
[root@test01 ~]# echo -e "\033[36m 蓝绿色字体 xiaoming \033[0m"
 蓝绿色字体 xiaoming 
[root@test01 ~]# echo -e "\033[37m 白色字体 xiaoming \033[0m"
 白色字体 xiaoming 
通过定义变量的方式给字体加颜色(推荐)
[root@test01 ~]# sh plush_color2.sh 
======read color========
====green color=======
====yellow color=====
======blue color=======
============pink color=======
[root@test01 ~]# cat plush_color2.sh 
#!/bin/sh
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'

echo -e "${RED_COLOR}======read color========${RES}"
echo -e "${GREEN_COLOR}====green color=======${RES}"
echo -e "${YELLOW_COLOR}====yellow color=====${RES}"
echo -e "${BLUE_COLOR}======blue color=======${RES}"
echo -e "${PINK}============pink color=======${RES}"

结合case语句给输出的字符串加颜色
[root@test01 ~]# sh plush_color3.sh 
I
am
xiaoming
[root@test01 ~]# vim plush_color3.sh 
[root@test01 ~]# cat plush_color3.sh 
#!/bin/sh

plus_color(){
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'

if [ $# -ne 2 ];then
    echo "Usage $0 content {red|yellow|blue|green|pink}"
    exit 0
fi
case "$2" in
    red|RED)
        echo -e "${RED_COLOR}$1${RES}"
        ;;
    yellow|YELLOW)
        echo -e "${YELLOW_COLOR}$1${RES}"
        ;;
    green|GREEN)
        echo -e "${GREEN_COLOR}$1${RES}"
        ;;
    blue|BLUE)
        echo -e "${BLUE_COLOR}$1${RES}"
        ;;
    pink|PINK)
        echo -e "${PINK}$1${RES}"
        ;;
    *)
        echo "Usage $0 content {red|yellow|blue|green|pink}"
        exit
esac
}

plus_color "I" red
plus_color "am" green
plus_color "xiaoming" blue

#!/bin/sh

function AddColor(){
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
PINK='\E[1;35m'
RES='\E[0m'

if [ $# -ne 2 ];then
    echo "Usage $0 content {red|yellow|blue|green|pink}"
    exit 0
fi
case "$2" in
    red|RED)
        echo -e "${RED_COLOR}$1${RES}"
        ;;
    yellow|YELLOW)
        echo -e "${YELLOW_COLOR}$1${RES}"
        ;;
    green|GREEN)
        echo -e "${GREEN_COLOR}$1${RES}"
        ;;
    blue|BLUE)
        echo -e "${BLUE_COLOR}$1${RES}"
        ;;
    pink|PINK)
        echo -e "${PINK}$1${RES}"
        ;;
    *)
        echo "Usage $0 content {red|yellow|blue|green|pink}"
        exit
esac
}

function main(){
    AddColor $1 $2
}
main $*
给输出的字符串加背景颜色(man console_codes)
[root@test01 ~]# 
[root@test01 ~]# echo -e "\033[40;37m 黑底白字 xiaoming\033[0m"
 黑底白字 xiaoming
[root@test01 ~]# echo -e "\033[41;37m 红底白字 xiaoming\033[0m"
 红底白字 xiaoming
[root@test01 ~]# echo -e "\033[42;37m 绿底白字 xiaoming\033[0m"
 绿底白字 xiaoming
[root@test01 ~]# echo -e "\033[43;37m 棕底白字 xiaoming\033[0m"
 棕底白字 xiaoming
[root@test01 ~]# echo -e "\033[44;37m 蓝底白字 xiaoming\033[0m"
 蓝底白字 xiaoming
[root@test01 ~]# echo -e "\033[45;37m 洋红底白字 xiaoming\033[0m"
 洋红底白字 xiaoming
[root@test01 ~]# echo -e "\033[46;37m 蓝绿底白字 xiaoming\033[0m"
 蓝绿底白字 xiaoming
[root@test01 ~]# echo -e "\033[47;37m 白底白字 xiaoming\033[0m"
 白底白字 xiaoming
[root@test01 ~]# echo -e "\033[47;30m 白底黑字 xiaoming\033[0m"
 白底黑字 xiaoming
[root@test01 ~]# cat add-openvpn-user
#!/bin/sh
#create
#time
#source function library
. /etc/init.d/functions
#config file path
FILE_PATH=/etc/openvpn_authfile.conf
[ ! -f $FILE_PATH ] && touch $FILE_PATH
usage(){
    cat <<EOF
    USAGE: `basename $0` {-add|-del|-search} username
EOF
}
#judge run user
if [ $UID -ne 0 ];then
    echo "you are not supper user,please call root!"
    exit 1;
fi
#judge arg bumbers
if [ $# -ne 2 ];then #传入的参数必须是2个
    usage
    exit 2
fi
#满足条件后进入case语句判断
case "$1" in 
    -a|-add)
        shift
        if grep "^$1$" ${FILE_PATH} >/dev/null 2>&1
          then
            action $"vpnuser,$1 is exist" /bin/false
            exit
        else
            chattr -i ${FILE_PATH}
            /bin/cp ${FILE_PATH} $FILE_PATH.${date +%F%T}
            echo "$1" >> ${FILE_PATH}
            [ $? -eq 0 ] && action $"Add $1" /bin/true
            chattr +i ${FILE_PATH}  
        fi
        ;;
    -d|-del)
        shift
        if [ `grep "\b$1\b" ${FILE_PATH}|wc -l` -lt 1 ]
          then
            action $"vpnuser,$1 is not exist." /bin/false
            exit
        else
            chattr -i ${FILE_PATH}
            /bin/cp ${FILE_PATH} $FILE_PATH.${date +%F%T}
            sed -i "/^${1}$d" ${FILE_PATH}
            [ $? -eq 0 ] && action $"Add $1" /bin/true
            chattr +i ${FILE_PATH}
            exit
        fi    
        ;;
    -s|-search)
        shift
        if [ `grep -w "$1" ${FILE_PATH}|wc -l` -lt 1 ]
          then
            echo $"vpnuser,$1 is not exist.";exit
        else
            echo $"vpnuser,$1 is exist.";exit
        fi
        ;;
    *)
        usage
        exit
        ;;
esac

grep精确过滤单词
[root@test01 ~]# grep -w "usage" add-openvpn-user
usage(){

[root@test01 ~]# grep  "\usage\b" add-openvpn-user

[root@test01 ~]# grep  "^usage$" add-openvpn-user

while循环语句
while <条件表达式>
do
    指令1。。。
done
[root@test01 ~]# while true;do uptime && sleep 2;done
 17:24:13 up 9 days,  3:19,  2 users,  load average: 0.00, 0.01, 0.05
 17:24:15 up 9 days,  3:19,  2 users,  load average: 0.00, 0.01, 0.05
 17:24:18 up 9 days,  3:19,  2 users,  load average: 0.00, 0.01, 0.05

sh w1.sh & 后台执行
bg  把当前任务放在后台执行
fg  把当前任务放在前台执行
jobs  查看当前执行的脚本
kill  killall pkill 杀掉进程
ps  查看进程
pstree  显示进程状态树
renice  改变优先权
nohup   用户退出后继续工作
pgrep   查找匹配条件的进程
strace  跟踪一个进程的系统调用情况
ltrace  跟踪进程调用库函数的情况

[root@test01 ~]# cat w2.sh 
#!/bin/sh
i=5
while ((i>0))
do
    echo "$i"
    ((i--))
done
[root@test01 ~]# sh w2.sh 
5
4
3
2
1
[root@test01 ~]# cat w2.sh 
#!/bin/sh
i=5
while [[ $i > 0 ]]
do
    echo "$i"
    ((i--))
done
[root@test01 ~]# cat w2.sh 
#!/bin/sh
i="$1"
while [ $i -gt 0 ]
do
    echo $i
    ((i--))
done
[root@test01 ~]# sh w2.sh 5
5
4
3
2
1
[root@test01 ~]# cat w2.sh 
#!/bin/sh
i=5
until [[ $i < 1 ]]
do
    echo $i
    ((i--))
done
[root@test01 ~]# sh w2.sh 
5
4
3
2
1
[root@test01 ~]# cat w3.sh
#!/bin/sh
i=1
sum=0
while ((i<=100))
do
    ((sum=sum+i))
    ((i++))
done
[ "$sum" -ne 0 ] && printf "totalsum is: $sum\n"
[root@test01 ~]# sh w3.sh
totalsum is: 5050
[root@test01 ~]# cat w3.sh
#!/bin/sh
i=100
((sum=i*(i+1)/2))
echo $sum
[root@test01 ~]# sh w3.sh
5050
[root@test01 ~]# cat w6.sh
#!/bin/sh
sum=1000
i=15
while ((sum>=i))
do
    ((sum=sum-i))
    [ $sum -lt $i ] && break
    echo "send message, left $sum"
done
echo "money is not enough:$sum"
[root@test01 ~]# cat w6.sh
#!/bin/sh
sum=1000
i=15
while ((sum>=i))
do
    ((sum=sum-i))
    [ $sum -lt $i ] && (
        echo "send message,left $sum money is not enough"
        break
    )
    echo "send message,left $sum"
done
[root@test01 ~]# cat wd1.sh
#!/bin/sh
file=$1
while true
do
    awk '{print $1}' $1 | grep -v "^$"|sort|uniq -c >/tmp/tmp.log
    exec </tmp/tmp.log
    while read line
    do
        ip=`echo $line|awk '{print $2}'`
        count=`echo $line|awk '{print $1}'`
        if [ $count -gt 500 ] && [ `iptables -L -n|grep "$ip"|wc -l` -lt 1 ];then
            iptables -I INPUT -s $ip -j DROP
            echo "$line is dropped." >>/tmp/droplist_$(date +%F).log
        fi
    done
    sleep 3600
done 
for循环语法
for 变量名 in 变量取值列表
do
    指令。。。
done
# for num in {1..9};do echo $num;done
# for i in `seq 5 -1 1`;do echo $i;done
# cd /tmp && for filename in `ls`;do echo $filename;done
[root@test01 tmp]# echo $filename
yum_save_tx.2022-09-01.14-25.BKvcCR.yumtx
[root@test01 tmp]# echo $filename |cut -d . -f1  #取出文件名部分(排除扩展名)
yum_save_tx
wd1.sh wd1 sh
word_length.sh word_length sh
批量取值
[root@test01 ~]# ls |awk -F "." '{print $0,$1,$2}'
wd1.sh wd1 sh
word_length.sh word_length sh
批量修改名
[root@test01 ~]# ls|awk -F "." '{print "mv",$0,$1"_finished."$2}'|bash
[root@test01 ~]# ls
1_finished.txt              jisuan_finished.sh      p_finished.sh  
批量改名
[root@test01 ~]# rename "_finished" "" *.sh
[root@test01 ~]# ls             
f3.sh          mysqlm2.sh  plush_color2.sh 


[root@test01 ~]# cat for1.sh 
#!/bin/sh
COLOR='\E[47;30m'
RES='\E[0m'
for num1 in `seq 9`
do
    for num2 in `seq 9`
    do
        if [ $num1 -ge $num2 ]
        then
            if ((num1*num2>9))
            then
                echo -en "${COLOR}${num1}x${num2}=$((num1*num2))$RES "
            else
                echo -en "${COLOR}${num1}x${num2}=$((num1*num2))$RES  "
            fi
        fi
    done
echo "  "
done
[root@test01 ~]# sh for1.sh 
1x1=1    
2x1=2  2x2=4    
3x1=3  3x2=6  3x3=9    
4x1=4  4x2=8  4x3=12 4x4=16   
5x1=5  5x2=10 5x3=15 5x4=20 5x5=25   
6x1=6  6x2=12 6x3=18 6x4=24 6x5=30 6x6=36   
7x1=7  7x2=14 7x3=21 7x4=28 7x5=35 7x6=42 7x7=49   
8x1=8  8x2=16 8x3=24 8x4=32 8x5=40 8x6=48 8x7=56 8x8=64   
9x1=9  9x2=18 9x3=27 9x4=36 9x5=45 9x6=54 9x7=63 9x8=72 9x9=81  

[root@test01 ~]# for ((i=0; i<5; i++));do curl http://www.baidu.com;done >>1.txt
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2381  100  2381    0     0  27291      0 --:--:-- --:--:-- --:--:-- 27367

for循环实现mysql分库备份的脚本
#mysql -uroot -pxiaoming123 -S /data/3306/mysql.sock -e "create database xiaoming;"
批量创建数据库
[root@test01 ~]# cat for2.sh 
#!/bin/sh
PATH="/application/mysql/bin:$PATH"
MYUSER=root
MYPASS=xiaoming123
SOCKET=/data/3306/mysql.sock
MYCMD="mysql -u$MYUSER -p$MYPASS -S $SOCKET"
for dbname in xiaoming1 xiaoming2 xiaoming3
do
    $MYCMD -e "create database $dbname"
done
备份每个库文件脚本
[root@test01 ~]# cat for2.sh 
#!/bin/sh
PATH="/application/mysql/bin:$PATH"
DBPATH=/server/backup
MYUSER=root
MYPASS=xiaoming123
SOCKET=/data/3306/mysql.sock
MYCMD="mysql -u$MYUSER -p$MYPASS -S $SOCKET"
MYDUMP="mysqldump -u$MYUSER -p$MYPASS -sSOCKET"
[ ! -d "$DBPATH" ] && mkdir $DBPATH
for dbname in `$MYCMD -e "show databases;" |sed '1,2d'|egrep -v "mysql|schema"`
do
    $MYDUMP $dbname|gzip >$DBPATH/${dbname}_$(date +%F).sql.gz
done
##
mysqldump -uroot -pxiaoming123 -S /data/3306/mysql.sock xiaoming lgzip >/server/backup/xiaoming_$(date +%F).sql.gz
###
批量建表并插入数据
[root@test01 ~]# cat for2.sh 
#!/bin/sh
PATH="/application/mysql/bin:$PATH"
MYUSER=root
MYPASS=xiaoming123
SOCKET=/data/3306/mysql.sock
MYCMD="mysql -u$MYUSER -p$MYPASS -S $SOCKET"
for dbname in xiaoming1 xiaoming2 xiaoming3
do
    $MYCMD -e "use $dbname;create table test(id int,name varchar(16); insert into test values(1,'testdata');)"
done
批量查看测试数据结果
[root@test01 ~]# cat for2.sh 
#!/bin/sh
PATH="/application/mysql/bin:$PATH"
MYUSER=root
MYPASS=xiaoming123
SOCKET=/data/3306/mysql.sock
MYCMD="mysql -u$MYUSER -p$MYPASS -S $SOCKET"
for dbname in xiaoming1 xiaoming2 xiaoming3
do
    $MYCMD -e "use $dbname;select * from $(dbname).test;"
done

  

 

[root@test01 ~]# cat for2.sh 
#!/bin/sh
PATH="/application/mysql/bin:$PATH"
DBPATH=/server/backup
MYUSER=root
MYPASS=xiaoming123
SOCKET=/data/3306/mysql.sock
MYCMD="mysql -u$MYUSER -p$MYPASS -S $SOCKET"
MYDUMP="mysqldump -u$MYUSER -p$MYPASS -sSOCKET"
[ ! -d "$DBPATH" ] && mkdir $DBPATH
for dbname in `$MYCMD -e "show databases;" |sed '1,2d'|egrep -v "mysql|schema"`  #登录获取所有的数据库名
do
    mkdir $DBPATH/$(dbname)_$(date +%F) -p  #创建对应目录
	for table in `$MYCMD -e "show tables from $dbname;"|sed '1d'` #获取每个库里的所有表然后循环
	do
	    $MYDUMP $dbname $table |gzip >$DBPATH/${dbname}_$(date +%F)/$(dbname)_${table}.sql.gz
		done
done

批量检查web服务是否正常,并发送相关邮件或手机报警信息
#!/bin/sh
path=/server/scripts   #定义脚本路径
MAIL_GROUP='111@qq.com 222@qq.com'  #邮件列表,以空格隔开
PAGER_GROUP='111 122'   #手机列表,以空格隔开
LOG_FILE='/tmp/web_check.log'   #日志路径

[ ! -d "$path" ] && mkdir -p $path #创建目录
function UrlList(){       #url列表函数
    cat >$path/domain.list<<EOF
    http://www.11.com
	http://www.baidu.com
EOF
}

function CheckUrl(){   #检测url的函数
    FAILCOUNT=0       #初始化失败的次数为0次
	for ((i=1;$i<=3;i++))  #检测3次
	do
	    wget -T 5 --tries=1 --spider $1 >/dev/null 2>&1  #具体访问url的命令,不输出信息
		if [ $? -ne 0 ]  #返回值如果不为0,则表示访问url失败了
		then
		    let FAILCOUNT+=1 #将失败的次数+1
		else
		    break  #如果返回值为0,则表示url成功了,跳出for循环,不做3次检测了
		fi
	done
	return $FAILCOUNT  #将失败次数作为返回值,凤凰函数外的脚本中
}
 
function MAIL(){     #定义邮件函数
    local SUBJECT_CONTENT=$1    #将函数的第1个传参赋值给主题变量
	for MAIL_USER in `echo $MAIL_GROUP`     #遍历邮件列表
	do
        mail -s "$SUBJECT_CONTENT " $MAIL_USER <$LOG_FILE  #发邮件
	done
}

function PAGER(){     #定义手机函数      
	for PAGER_USER in `echo $PAGER_GROUP`    #遍历手机列表
	do
	    TITLE=$1             #函数的第1个传参赋值给主题变量
		CONTACT=$PAGER_USER  #手机号赋值给CONTACT变量 
		HTTPGW=http://www.baidu.com  #发短信地址,可以用微信替代
		#send message
		curl -d cdkey=5ADF-EFA -d password=xiaoming -d phone=$CONTACT -d message='$TITLE[$2]' $HTTPGW
		#发送短信报警。
	done
}

function SendMsg(){  #定义发送消息的函数
    if [ $1 -ge 3 ];then  #如果失败的次数大于等于3,那么这里的$1是函数的传参,接收访问url失败的次数。
	    RETVAL=1        
		NOW_TIME=`date +"%Y-%m-%d %H:%M:%S"`    #报警时间
		SUBJECT_CONTENT='http://$2 is error,${NOW_TIME}.'  #报警主题
		echo -e "$SUBJECT_CONTENT" |tee $LOG_FILE  #输出信息,并记录到日志
		MAIL $SUBJECT_CONTENT           #发送报警邮件,$SUBJECT_CONTENT将作为函数参数传给MAIL函数体的$1
		
		PAGER $SUBJECT_CONTENT $NOW_TIME    
		#发送报警邮件,$SUBJECT_CONTENT将作为函数参数传给MAIL函数体的$1,$NOW_TIME作为函数体给$2
	else  #如果失败的次数不大于3,则认为url是好的
	    echo "http://$2 is ok" #打印ok
		RETVAL=0   #以0作为返回值
	fi  
	return $RETVAL  
}

function main(){  #定义函数
    UrlList       #加载url列表
	for url in `cat $path/domain.list`  #读取url列表
	do
	    CheckUrl $url  #传入url给检测url的函数进行检查
		SendMsg $? $url  #传入第1参数$?,即CheckUrl里的返回值(用检测失败的次数作为返回值),传入的第2个参数为检测的url
	done
}
main



批量创建用户及密码
[root@test01 ~]# cat p1.sh 
#!/bin/sh

. /etc/init.d/functions
user="xiaoming"
passfile="/root/user.log"
for num in `seq -w 11 15`
do
    pass="`echo "test $RANDOM"|md5sum|cut -c3-11`"
    useradd $user$num &>/dev/null &&\
    echo "$pass"|passwd --stdin $user$num &>/dev/null &&\
    echo -e "user:$user$num\tpasswd:$pass" >>$passfile
    if [ $? -eq 0 ]
    then
        action "$user$num is ok" /bin/true
    else
        action "$user$num is fail" /bin/false
    fi
done
echo --------------------
cat $passfile && >$passfile
[root@test01 ~]# sh p1.sh
xiaoming11 is ok                                           [  OK  ]
xiaoming12 is ok                                           [  OK  ]
xiaoming13 is ok                                           [  OK  ]
xiaoming14 is ok                                           [  OK  ]
xiaoming15 is ok                                           [  OK  ]
--------------------
user:xiaoming11	passwd:6a09827f1
user:xiaoming12	passwd:72a2ec4e0
user:xiaoming13	passwd:37de721c2
user:xiaoming14	passwd:6d2edc2c3
user:xiaoming15	passwd:806f1ad6f
批量删除用户
[root@test01 ~]# for i in `seq 11 15`;do userdel xiaoming$i;done
通过openssl产生的随机数
[root@test01 ~]# openssl rand -base64 8
vbOq7O8cYLo=
[root@test01 ~]# openssl rand -base64 80
I+gOFdH2U6asmgcbPwqT1pzoJJIbvCP8a3GpkWlWz+6PoAPhiCm0bK/5c0Ut1P22
/SUeL4LWFNb81m+2D6eEsiPXXSlKyJMjcdvXOLaTYmY=
通过date获得的随机数
[root@test01 ~]# date +%s%N
1663209984094487150
[root@test01 ~]# date +%s%N
1663210021560285280
通过获得的随机数
[root@test01 ~]# head /dev/urandom |cksum
2933324643 2509
[root@test01 ~]# head /dev/urandom |cksum
294941461 2490
通过UUID获得的随机数
[root@test01 ~]# cat /proc/sys/kernel/random/uuid 
9c1c6461-6238-4358-9c43-b3edbccf45c0
使用expect附带的mkpasswd生成随机数

通过读取txt文件的文件名,批量创建用户及密码
[root@test01 ~]# cat p1.sh 
#!/bin/sh

. /etc/init.d/functions
user="/root/ps1.txt"
passfile="/root/user.log"
for num in `cat $user`
do
    pass="`echo "test $RANDOM"|md5sum|cut -c3-11`"
    useradd $num &>/dev/null &&\
    echo "$pass"|passwd --stdin $num &>/dev/null &&\
    echo -e "user:$num\tpasswd:$pass" >>$passfile
    if [ $? -eq 0 ]
    then
        action "$num is ok" /bin/true
    else
        action "$num is fail" /bin/false
    fi
done
echo --------------------
cat $passfile && >$passfile
[root@test01 ~]# cat ps1.txt 
xiaoming
xiaoli
xiaogang
xiaohong
执行脚本
[root@test01 ~]# sh p1.sh 
xiaoming is ok                                             [  OK  ]
xiaoli is ok                                               [  OK  ]
xiaogang is ok                                             [  OK  ]
xiaohong is ok                                             [  OK  ]
--------------------
user:xiaoming	passwd:ba0c17690
user:xiaoli	passwd:9bbb0eafd
user:xiaogang	passwd:3c22129e8
user:xiaohong	passwd:0de2cbfe6
批量删除用户
[root@test01 ~]# for i in `cat ps1.txt`;do userdel $i;done
select循环语句
select 变量名 [ in 菜单取值列表 ]
do
    指令。。。
done

#select name [in word];do list;done 
在此结构中"in 变量取值列表" 可省略,省略时相当于使用in "$@",使用for i就相当于使用for i in "$@"
[root@test01 ~]# select name in xiaoming xiaoli xiaohong;do echo $name;done
1) xiaoming
2) xiaoli
3) xiaohong
#? 1
xiaoming
#? 2
xiaoli
#? 3
xiaohong
#? test  #输入错误则返回空

# select name in `ls /root`;do echo $name;done

循环控制和状态返回值的应用
break n  如果省略n,则表示跳出整个循环,n 表示跳出循环的层数
continue n 如果省略你,则表示跳过本次循环,忽略本次循环的剩余代码,进入循环的下一次循环。n 表示退到第n层继续循环
exit n  退出当前shell程序,n为上一次程序执行的状态返回值。在下一个shell里可以通过$?接收exit n 的n值
return n 用于在函数里作为函数的返回值,以判断函数执行是否正确。在下一个shell里可以通过$?接收return n的n值


route add -net 10.176.8.0 netmask 255.255.255.0 gw 10.176.8.247

[root@test01 ~]# cat b1.sh 
#!/bin/sh

if [ $# -ne 1 ];then
    echo $"usage:$0 {break|continue|exit|return}"
    exit 1
fi
test(){
    for ((i=0; i<=5; i++))
    do
        if [ $i -eq 3 ];then
            $*;     #接收函数外的参数,就是{break|continue|exit|return}其中的一个
        fi
        echo $i
    done
    echo "I am in func."
}
test $*  #为函数的传参
func_ret=$?  #接收并测试函数的返回值
if [ `echo $*|grep return|wc -l` -eq 1 ];then
    echo "return's exit status:$func_ret"
fi
echo "OK"
[root@test01 ~]# sh b1.sh 
usage:b1.sh {break|continue|exit|return}
[root@test01 ~]# sh b1.sh break
0
1
2
I am in func.
OK
[root@test01 ~]# sh b1.sh continue
0
1
2
4
5
I am in func.
OK
[root@test01 ~]# sh b1.sh exit
0
1
2
[root@test01 ~]# sh b1.sh return
0
1
2
return's exit status:0
OK

shell数组
语法
array=(value1 value2 value3 ...)
[root@test01 ~]# array=(1 2 3)  #用小括号将数组内容赋值给数组变量,数组元素用空格分隔开。
[root@test01 ~]# echo $array
1
[root@test01 ~]# echo $array[*]
1[*]
[root@test01 ~]# echo ${array[*]} #输出上面定义的数组的所有元素值,注意语法;使用*或@ky 得到整改数组的内容
1 2 3
方法2用小括号将变量值括起来,同时采用键值对的形式赋值
[root@test01 ~]# array=([1]=one [2]=two [3]=three)
[root@test01 ~]# echo ${array[*]}
one two three
[root@test01 ~]# echo ${array[1]}
one
[root@test01 ~]# echo ${array[2]}
two
[root@test01 ~]# echo ${array[3]}
three
方法3
[root@test01 ~]# array[0]=a;array[1]=b;array[2]=c
[root@test01 ~]# echo ${array[0]}
a
[root@test01 ~]# echo ${array[2]}
c
方法4
[root@test01 ~]# mkdir array -p
[root@test01 ~]# touch array/{1..3}.txt
[root@test01 ~]# ls -l array/
total 0
-rw-r--r-- 1 root root 0 Sep 19 10:10 1.txt
-rw-r--r-- 1 root root 0 Sep 19 10:10 2.txt
-rw-r--r-- 1 root root 0 Sep 19 10:10 3.txt
[root@test01 ~]# array=($(ls array))
[root@test01 ~]# echo ${array[*]}  #使用*或@ky 得到整改数组的内容
1.txt 2.txt 3.txt
[root@test01 ~]# echo ${array[@]}  #使用*或@ky 得到整改数组的内容
1.txt 2.txt 3.txt
[root@test01 ~]# echo ${array[0]}
1.txt
[root@test01 ~]# echo ${array[1]}
2.txt
[root@test01 ~]# echo ${array[2]}
3.txt

数组的删除 unset 数组[下标]
unset array[1]
[root@test01 ~]# unset array[1]
[root@test01 ~]# echo ${array[*]}
1.txt 3.txt
[root@test01 ~]# ll array/   #并没有删除2.txt,只是删除了数组的元素
total 0
-rw-r--r-- 1 root root 0 Sep 19 10:10 1.txt
-rw-r--r-- 1 root root 0 Sep 19 10:10 2.txt
-rw-r--r-- 1 root root 0 Sep 19 10:10 3.txt

数组的添加
[root@test01 ~]# array[1]=5.txt
[root@test01 ~]# echo ${array[*]}
1.txt 5.txt 3.txt

数组内容的截取和替换
[root@test01 ~]# array=(1 2 3 4 5)
[root@test01 ~]# echo ${array[@]:1:3}  #截取1号到3号数组元素
2 3 4
[root@test01 ~]# array=($(echo {a..z}))  #将变量的结果赋值给数组
[root@test01 ~]# echo ${array[*]}
a b c d e f g h i j k l m n o p q r s t u v w x y z
[root@test01 ~]# echo ${array[@]:1:3}  #截取下标为1到3的数组元素
b c d
[root@test01 ~]# echo ${array[@]:0:2} #截取下标为0到2的数组元素
a b
[root@test01 ~]# array=(1 2 3 1 1)
[root@test01 ~]# echo ${array[@]/1/b}  #把数组中的1替换成b,原数组未被修改,和sed相似
b 2 3 b b
[root@test01 ~]# echo ${array[*]}
1 2 3 1 1
删除数组元素部分内容
[root@test01 ~]# array=(one two three four five)
[root@test01 ~]# echo ${array[@]}
one two three four five
[root@test01 ~]# echo ${array[@]#o*}  #从左边开始匹配最短的数组元素,并删除
ne two three four five
[root@test01 ~]# echo ${array[@]}
one two three four five
[root@test01 ~]# echo ${array[@]##o*}  #从左边开始匹配最长的数组元素,并删除
two three four five
[root@test01 ~]# echo ${array[@]}
one two three four five
[root@test01 ~]# echo ${array[@]%f*} #从右边开始匹配最短的数组元素,并删除
one two three
[root@test01 ~]# echo ${array[@]%%f*}  #从右边开始匹配最长的数组元素,并删除
one two three
通过C语音型的for循环打印数组元素
[root@test01 ~]# cat a1.sh 
#!/bin/sh
array=(1 2 3 4 5)
for ((i=0;i<${#array[*]};i++))
do
    echo ${array[i]}
done
[root@test01 ~]# sh a1.sh 
1
2
3
4
5
通过普通的for循环打印数组元素
[root@test01 ~]# cat a2.sh 
#!/bin/sh
array=(1 2 3 4 5)
for n in ${array[*]}
do
    echo $n
done
[root@test01 ~]# sh a2.sh 
1
2
3
4
5
使用while循环打印数组元素
[root@test01 ~]# cat a3.sh 
#!/bin/sh
array=(1 2 3 4 5)
i=0
while ((i<${#array[*]}))
do
    echo ${array[i]}
    ((i++))
done
[root@test01 ~]# sh a3.sh 
1
2
3
4
5
对于元素特别长的情况,可以将其竖向列出来,看起来更规范工整
[root@test01 ~]# cat a4.sh
#!/bin/sh
array=(
xiaoming
xiaoli
xiaohong
xiaobai
)
for ((i=0; i<${#array[*]}; i++))
do
    echo "This is num $i, then content is ${array[$i]}"
done
[root@test01 ~]# sh a4.sh
This is num 0, then content is xiaoming
This is num 1, then content is xiaoli
This is num 2, then content is xiaohong
This is num 3, then content is xiaobai

[root@test01 ~]# cat a5.sh
#!/bin/sh
dir=($(ls array))        #把ls array的结果放进数组里
for ((i=0; i<${#dir[*]}; i++))   #${#dir[*]} 为数组的长度
do
    echo "This is NO.$i,filename is ${dir[$i]}"
done
[root@test01 ~]# sh a5.sh
This is NO.0,filename is 1.txt
This is NO.1,filename is 2.txt
This is NO.2,filename is 3.txt
数组的重要命令
(1)定义命令
静态数组
array=(1 2 3)
动态数组
array=($(ls))
为数组赋值
array[2]=3
(2)打印命令
打印所有元素
${array[@]} 或${array[*]}
打印数组长度
${#array[@]}或${#array[*]}
打印单个元素
${array[i]} #是数组的下标
(3)循环打印的常用基本语法
#!/bin/sh
arr=(
10.0.0.1
10.0.0.2
10.0.0.3
)
C语言for循环语法
for ((i=0; i<${#array[@]}; i++))
do
    echo "${arr[$i]}"
done
echo ----------------------
普通for循环语法
for n in ${arr[*]}
do
    echo "$n"
done 
计算变量内容的长度,4种
[root@test01 ~]# char=xiaoming
[root@test01 ~]# echo $char|wc -L
8
[root@test01 ~]# echo ${#char}
8
[root@test01 ~]# expr length $char
8
[root@test01 ~]# echo $char|awk '{print length($0)}'
8
打印字母数不大于6的单词
[root@test01 ~]# cat a6.sh
#!/bin/sh
arr=(I am xiaoming teacher welcome to xiaoming training class)
for ((i=0; i<${#arr[@]}; i++))
do
    if [ ${#arr[$i]} -lt 6 ]
    then
        echo "${arr[$i]}"
    fi
done
echo -------------------
for word in ${arr[*]}
do
    if [ `expr length $word` -lt 6 ]
    then
        echo $word
    fi
done
[root@test01 ~]# sh a6.sh
I
am
to
class
-------------------
I
am
to
class
同时检测多个URL是否正常
[root@test01 ~]# cat a7.sh 
#!/bin/sh
. /etc/init.d/functions

check_count=0
url_list=(              #定义检测url数组,包含多个url地址
http://www.baidu.com
http://abc.com
http://123.com
)

function wait (){                   #定义 3 2 1 倒计时函数
    echo -n '3秒后,执行检测URL操作。';
    for ((i=0; i<3; i++))
    do
        echo -n ".";sleep 1
    done
    echo
}

function check_url(){           #定义检测url函数
    wait                         #执行倒计时函数   
    for ((i=0; i<`echo ${#url_list[*]}`; i++))    #循环数组元素
    do
        wget -o /dev/null -T 3 --tries=1 --spider ${url_list[$i]} >/dev/null 2>&1
		#检测是否可以访问数组元素的地址
        if [ $? -eq 0 ]       #如果返回值为0, 则表示访问成功
        then
            action "${url_list[$i]}" /bin/true    #优雅的显示成功结果
        else
            action "${url_list[$i]}" /bin/false    #优雅的显示失败结果
        fi
    done
    ((check_count++))        #检测次数加1            
}

main(){              #定义主函数
    while true       #开启一个持续循环
    do
        check_url    #加载检测url的函数    
        echo "-----------check count:${check_count}--------"
        sleep 10     #间歇10秒
    done
}

main   #调用主函数运行程序
[root@test01 ~]# sh a7.sh 
3秒后,执行检测URL操作。...
http://www.baidu.com                                       [  OK  ]
http://abc.com                                             [  OK  ]
http://123.com                                             [FAILED]
-----------check count:1--------
3秒后,执行检测URL操作。...
http://www.baidu.com                                       [  OK  ]
http://abc.com                                             [  OK  ]
http://123.com                                             [FAILED]


利用echo调试一个简单的判断脚本
[root@test01 ~]# cat e1.sh
#!/bin/sh
read -p "pls input two num:" a b
echo $a $b
exit
#####
#if [ $a -lt $b ]
if (($a < $b))
then
    echo "$a < $b"
elif [ $a -eq $b ]
then
    echo "$a = $b"
else
    echo "$a > $b"
fi
[root@test01 ~]# sh e1.sh
pls input two num:2 3
2 3
[root@test01 ~]# sh e1.sh
pls input two num:3 5
3 5
3 < 5

使用bash命令参数调试
sh  [-nvx]  scripts.sh
-n 不会执行该脚本,仅检查脚本语法是否有问题,并给出错误提示
-v 在执行脚本时,先将脚本的内容输出到屏幕上,然后执行脚本,如果有错误,也会给出错误提示
-x 将执行的脚本内容及输出显示到屏幕上,这是对调试很有用的参数

配置文件.vimrc的重要参数介绍
#~/.vimrc
##########
#全局设置
#关闭兼容模式
set nocompatible
设置历史记录步数
set history=100
开启相关插件
filetype on
filetype plugin on
filetype indent on 
当文件在外部被修改时,自动更新该文件
set autoread
激活鼠标的使用
set mouse=a 
############
#字体和颜色
#开启语法 
syntax enable
设置字体
set guifount=dejaVu\ Sans\ MONO\ 10
设置颜色 
colorscheme desert
高亮显示当前行
set cursorline 
hi cursorline guibg=#00ff00
hi CursorColumn guibg=#00ff00 
#############
#代码折叠功能
#激活折叠功能
set foldenable
#设置安装语法方式折叠(可简写set fdm=XX)
#有6种折叠方法
#manual 手工折叠
#indent 更多的缩进表示更高级别的折叠
#expr 用表达式来定义折叠
#syntax 用语法高亮来定义折叠
#diff 对没有更改的文本进行折叠
#marker 对中文的标志进行折叠
set foldmethod=manual
#设置折叠区域的宽度
#如果不为0, 则在屏幕左侧显示一个折叠标识列
#分别'-'和'+'来表示打开和关闭的折叠
set foldcolumn=0
设置折叠层数为3
setlocal foldlevel=3
设置为自动关闭折叠
set foldclose=all
用空格键来代替zo和zc快捷键实现开关折叠
#zo O-pen a fold 打开折叠
#zc C-lose a fold 关闭折叠
#zf F-old creation 创建折叠
nnoremap <space> @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')<CR>
############
#文字处理
#使用空格来替换Tab
set expandtab
#设置所有的Tab和缩进为4个空格
set tabstop=4
#设定<< 和 >> 命令移动时的宽度为4
set shiftwidth=4
#使得按退格键时可以一次删掉4个空格
set softtabstop=4
set smarttab
#缩进,自动缩进(继承前一行的缩进)
#set autoindent命令关闭自动缩进,是下面配置的缩写
#可使用autoindent命令的简写,即 ":set ai" 和 ":set noai"
#还可以使用" :set ai sw=4" 在一个命令中打开缩进并设置缩进级别
set ai
#智能缩进
set si
#自动缩进 
set wrap 
#设置软宽度
set sw=4
#############
#vim 
#Turn on WiLd menu 
set wildmenu
#显示标尺
set ruler
#设置命令行的高度
set cmdheight=1
#显示行数
set nu 
#Do not redraw, whe running macros.. lazyredraw
set lz
#设置退路
set backspace=eol,start,indent
#Bbackspace and cursor keys wrap to 
set whichwrap+=<,>,h,l 
#Set magic on(设置魔术)
set magic
#关闭遇到错误时的声音提示
#关闭错误信息响铃
set noerrorbells
#关闭使用可视响铃代替呼叫
set novisualbell 
#显示匹配的括号({[和]})
set showmatch
#how many tenths of a secound to blink
set mat=2
#搜索时高亮显示搜索到的内容
set hlsearch
#搜索时不区分大小写
#还可以使用简写(':set ic' and ':set noic')
set ignorecase
##############
#编码设置
set encoding=utf-8
#设置文件编码
set fileencodings=utf-8
#设置终端编码
set termencoding=utf-8
#############
#其他设置
#############
#开启新行时使用智能自动缩进
set smartindent
set cin
set showmatch
#隐藏工具栏
set guioptions-=T
#隐藏菜单栏
set guioptions-=m 
#置空错误铃声的终端代码
set vb t_vb=
#显示状态栏(默认值为1,表示无法显示状态栏)
set laststatus=2
#粘贴不换行问题的解决方法
set pastetoggle=<F9>
#设置背景色
set background=dark
#设置高亮相关
highlight Search ctermbg-black ctermfg=white guifg=while guigb=black
在shell脚本的开头自动增加解释器及作者的相关版权信息
autocmd BufNewFile *.py,*.cc,*.sh,*.java exec ":call Set Title()"
func SetTitle()
    if expand("%:e") == 'sh'
	    call setline(1, "#!/bin/bash")
		call setline(2, "#Author:xiaoming")
		call setline(3, "#Blog:http://xiaoming.com")
		call setline(4, "#Time:".strftime("%F %T"))
		call setline(5, "#Name:".expand("%"))
		call setline(6, "#Version:V1.0")
		call setline(7, "Description:This is a test script.")
	endif
endfunc
[root@test01 ~]# cat /root/.vimrc 
set nocompatible
set history=100
filetype on
filetype plugin on
filetype indent on 
set autoread
set mouse=a 
syntax enable
colorscheme desert
set cursorline 
set foldenable
set foldmethod=manual
set foldcolumn=0
setlocal foldlevel=3
set foldclose=all
nnoremap <space> @=((foldclosed(line('.')) < 0) ? 'zc' : 'zo')<CR>
set expandtab
set tabstop=4
set shiftwidth=4
set softtabstop=4
set smarttab
set ai
set si
set wrap 
set sw=4
set wildmenu
set ruler
set cmdheight=1
set nu 
set lz
set backspace=eol,start,indent
set whichwrap+=<,>,h,l 
set magic
set noerrorbells
set novisualbell 
set showmatch
set mat=2
set hlsearch
set ignorecase
set encoding=utf-8
set fileencodings=utf-8
set termencoding=utf-8
set smartindent
set cin
set showmatch
set guioptions-=T
set guioptions-=m 
set vb t_vb=
set laststatus=2
set pastetoggle=<F9>
set background=dark
autocmd BufNewFile *.py,*.cc,*.java exec ":call Set Title()"
func SetTitle()
    if expand("%:e") == 'sh'
		call setline(7, "Description:This is a test script.")
	endif
endfunc


P307 vim编辑器常用操作

并发ping方案
[root@test01 ~]# cat ping1.sh 
#!/bin/sh
CMD="ping -W 2 -c 2"
Ip="10.227.6."
for n in $(seq 254)
do
    {
    $CMD $Ip$n &> /dev/null
    if [ $? -eq 0 ];then
        echo "$Ip$n is ok"
    fi
    }&
done
监控缓存服务
[root@test01 ~]# cat memcached2.sh 
#!/bin/sh
if [ `netstat -ntlpu|grep 11211|wc -l` -lt 1 ]
then
    echo "Memcached Service is error."
    exit 1
fi
printf "del key\r\n"|nc 127.0.0.1 11211 &>/dev/null
printf "set key 0 0 10 \r\nxiaoming123\r\n"|nc 127.0.0.1 11211 &>/dev/null
McValues=`printf "get key\r\n"|nc 127.0.0.1 11211|grep xiaoming123|wc -l`
if [ $McValues -eq 1 ]
then
    echo "Memcached status is ok"
else
    echo "Memcached status is bad"
fi
[root@test01 ~]# printf "get key\r\n"|nc 127.0.0.1 11211|grep xiaoming123|wc -l
0

脚本实现入侵检测和报警
(1)建立测试数据
[root@test01 ~]# mkdir /var/html/www -p
[root@test01 ~]# cp -a /etc/a* /var/html/www/
[root@test01 ~]# cp -a /etc/b* /var/html/www/
[root@test01 ~]# ls /var/html/www/
adjtime  aliases.db    anacrontab   audisp  bash_completion.d  binfmt.d
aliases  alternatives  asound.conf  audit   bashrc
[root@test01 ~]# 
建立初始的文件指纹库
[root@test01 ~]# find /var/html/www/ -type f|xargs md5sum >/opt/zhiwei.db.org
[root@test01 ~]# tail /opt//zhiwei.db.org 
199eaa1e43fa9139f0910bdb64fd219e  /var/html/www/audisp/plugins.d/af_unix.conf
57421191efe78160bd7e085de99bf5cd  /var/html/www/audisp/plugins.d/syslog.conf
45dc8b93a8b644d96197dc87b7b2b392  /var/html/www/audit/audit-stop.rules
29f4c6cd67a4ba11395a134cf7538dbd  /var/html/www/audit/auditd.conf
36ffbc8f4c0800b1b8fbd35191782d82  /var/html/www/audit/rules.d/audit.rules
f1c2a2ef86e5db325cd2738e4aa7df2c  /var/html/www/audit/audit.rules
1215cec8b7cc508972f66f19e46f65b1  /var/html/www/bash_completion.d/iprutils
7ca61969ad2fbb5fe8ce81f0be130f13  /var/html/www/bash_completion.d/yum-utils.bash
b8343ef4bb32a1573a472d6623228791  /var/html/www/bash_completion.d/perf
3f48a33cc1fce59ff2df86429151c0e0  /var/html/www/bashrc
建立初始的文件库
[root@test01 ~]# find /var/html/www/ -type f >/opt/wenjian.db.ori
[root@test01 ~]# tail /opt/wenjian.db.ori 
/var/html/www/audisp/plugins.d/af_unix.conf
/var/html/www/audisp/plugins.d/syslog.conf
/var/html/www/audit/audit-stop.rules
/var/html/www/audit/auditd.conf
/var/html/www/audit/rules.d/audit.rules
/var/html/www/audit/audit.rules
/var/html/www/bash_completion.d/iprutils
/var/html/www/bash_completion.d/yum-utils.bash
/var/html/www/bash_completion.d/perf
/var/html/www/bashrc
按单词出现的频率
awk数组法
[root@test01 ~]# awk -F "[,. ]" '{for(i=1;i<NF;i++)array[$i]++} END{for(key in array)print array[key],key|"sort -nr"}' 2.txt|column -t
sort排序法
[root@test01 ~]# tr "[ ,.]" "\n"<2.txt|grep -v "^$"|sort|uniq -c |sort -rn
tr配合awk数组法
[root@test01 ~]# tr "[ ,.]" "\n"<2.txt|sed '/^$/d'|awk '{++S[$0]}END{for(key in S)print S[key]" " key|"sort -rn"}'
按字母出现的频率降序排序
awk数组法
[root@test01 ~]# tr "{ |,|.}" "\n" <2.txt|awk -F "" '{for(i=1;i<=NF;i++)array[$i]++}END{for(key in array)print array[key],key|"sort -nr"}'
grep及sort排序法
[root@test01 ~]# grep -o "[^ ]" 2.txt|sort|uniq -c|sort -rn -k1

检测服务是否正常2
[root@test01 ~]# cat pingts1.sh
#!/bin/sh
#ping test
WEB1=www.baidu.com

while true
do
    ping -w2 -c2 $WEB1 >/dev/null 2>&1
    if [ $? -ne 0 ];then
        echo "`date +"%Y-%m-%d %H:%M:%S"` sorry, ping not done1 !"
    else
        echo "`date +"%Y-%m-%d %H:%M:%S"` yes,baidu.com is good !"
    fi
    sleep 5
done

  

 

 

 

 

 

 

 

 

 

 

 

 

 

2,常用命令汇总

  

关机:
一分钟后关机 #shutdown  -h  +1  (1代表1分钟)

重启
#shutdown -r  now
/etc/inittab   0代表关机,6表示重启

shutdown -r  11:00  (11:00表示11点重启)

halt 、 poweroff、reboot
# ll /sbin/poweroff 
lrwxrwxrwx 1 root root 16 Mar 16 17:22 /sbin/poweroff -> ../bin/systemctl
[root@yt-stor-r60-25 ~]# ll /sbin/halt 
lrwxrwxrwx 1 root root 16 Mar 16 17:22 /sbin/halt -> ../bin/systemctl


cd  参数 -
# cd -   切换到上一个旧目录
# cd ~   切换到家目录


tree 
#tree  -a /tmp  显示目录下的所有内容(-a)
#tree  -d /tmp  显示目录下目录,不显示文件(-d)

-f 显示完整路径名称, 
-i  显示完整路径名称,则不显示树形部分
#tree  -f /tmp 
#tree  -i /tmp 





#
# cat /etc/resolv.conf 
nameserver 10.176.13.90
# showmount -e ifswh8.wh2.local
# mkdir /ifswh8
# mount ifswh8.wh2.local:/ifs/data/all   /ifswh8


find命令和xargs命令
xargs 传参
将一个命令输出转成命令参数传递给后续命令
选项: -a 从文件中读入作为输入
       -n  后面加次数,表示执行一次用几个参数,默认使用
	   -t  先打印,再执行
	   -I  或者i看系统支持{ }替换字符,表示文件内容

~]#ls -l |xargs ls -lhi
~]#ls -l |xargs -t ls -lhi
~]#find . -type f|xargs sed -i 's#xxxxxx##g'  查找文件后,替换xxxxxx为空

 


 

 

 

3,脚本

 

  

posted on 2022-07-14 15:43  微子天明  阅读(28)  评论(1编辑  收藏  举报

导航