Shell编程之数组

一、Shell数组

1.什么是Shell数组

是一个元素集合,它把有限个元素(变量或字符内容)用一个名字来命名,然后用编号对它们进行区分。

2.Shell数组的定义

方法1:
array=(value1 value2 value3 ...)

[root@codis-178 ~]# array=(1 2 3)
[root@codis-178 ~]# echo ${array[*]}
1 2 3

方法2:
array=([1]=one [2]=two [3]=three)

[root@codis-178 ~]# array=([1]=one [2]=two [3]=three)
[root@codis-178 ~]# echo ${array[*]}
one two three
[root@codis-178 ~]# echo ${array[1]}
one
[root@codis-178 ~]# echo ${array[2]}
two
[root@codis-178 ~]# echo ${array[3]}
three

3.Shell数组的输出

(1)打印数组元素

[root@codis-178 ~]# array=(one two three)
[root@codis-178 ~]# echo ${array[1]}
two
[root@codis-178 ~]# echo ${array[2]}
three
[root@codis-178 ~]# echo ${array[@]}
one two three

(2)打印数组元素的个数

[root@codis-178 ~]# echo ${array[*]}
one two three
[root@codis-178 ~]# echo ${#array[*]}
3
[root@codis-178 ~]# echo ${#array[@]}
3

(3)数组赋值

[root@codis-178 ~]# array[3]=four
[root@codis-178 ~]# echo ${array[*]}
one two three four
[root@codis-178 ~]# array[0]=lodboy
[root@codis-178 ~]# echo ${array[*]}
lodboy two three four

(4)数组的删除

[root@codis-178 ~]# echo ${array[*]}
lodboy two three four
[root@codis-178 ~]# unset array[1]
[root@codis-178 ~]# echo ${array[*]}
lodboy three four
[root@codis-178 ~]# unset array[0]
[root@codis-178 ~]# echo ${array[*]}
three four

(5)数组内容的截取和替换

截取:
[root@codis-178 ~]# array=(1 2 3 4 5)
[root@codis-178 ~]# echo ${array[@]:1:3}
2 3 4
[root@codis-178 ~]# array=($(echo {a..z}))
[root@codis-178 ~]# 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@codis-178 ~]# echo ${array[@]:1:3}
b c d
[root@codis-178 ~]# echo ${array[@]:0:2}
a b

替换(不会改变原先数组的内容):
[root@codis-178 ~]# array=(1 2 3 1 1)
[root@codis-178 ~]# echo ${array[@]/1/b}
b 2 3 b b

二、Shell数组的实践

1.简单实现

(1)使用循环批量输出数组的元素

[root@codis-178 ~]# cat 13_1.sh
#!/bin/bash
array=(1 2 3 4 5)
for((i=0;i<${#array[*]};i++))
do
	echo ${array[i]}
done
[root@codis-178 ~]# sh 13_1.sh
1
2
3
4
5

(2)通过竖向列举定义数组元素并批量打印

[root@codis-178 ~]# cat 13_2.sh
#!/bin/bash
array=(
oldboy
oldgirl
xiaotong
bingbing
)
for((i=0;i<${#array[*]};i++))
do
	echo ${array[i]}
done
echo "array len:${#array[*]}"
[root@codis-178 ~]# sh 13_2.sh
oldboy
oldgirl
xiaotong
bingbing
array len:4

(3)将命令结果作为数组元素定义并打印

[root@codis-178 ~]# mkdir -p array
[root@codis-178 ~]# touch array/{1..3}.txt
[root@codis-178 ~]# ls array/
1.txt  2.txt  3.txt

[root@codis-178 ~]# cat 13_3.sh
#!/bin/bash
dir=($(ls array/))
for((i=0;i<${#dir[*]};i++))
do
	echo "This is NO.$i,filename is ${dir[$i]}"
done
[root@codis-178 ~]# sh 13_3.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

2.Shell数组的重要命令

(1)定义命令
静态
array=(1 2 3)
动态
array=($(ls))
赋值
array[3]=4

(2)打印命令
所有元素
${array[@]}或${array[]}
长度
${#array[@]}或${#array[
]}
单个元素
${array[i]}

3.Shell数组实战

(1)利用bash for循环打印下面这句话中字母数不大于6的单词
I am oldboy teacher welcome to oldboy trainning class

[root@codis-178 ~]# cat 13_4.sh
#!/bin/bash

arr=(I am oldboy teacher welcome to oldboy trainning class)
for((i=0;i<${#arr[*]};i++))
do
	if [ ${#arr[i]} -lt 6 ]
		then
			echo "${arr[i]}"
	fi
done

[root@codis-178 ~]# sh 13_4.sh
I
am
to
class

(2)批量检查多个网站地址是否正常
要求:
1)使用数组
2)每5秒进行一次全部检测,无法访问报警
3)检测地址:
http://www.baidu.com
http://www.163.com
http://www.anzhi.com

[root@codis-178 ~]# cat 13_5.sh
#!/bin/bash
. /etc/init.d/functions

eheck_count=0
url_list=(
http://www.baidu.com
http://www.163.com
http://www.anzhi.com
)

function wait(){
	echo -n '3秒后。执行检查URL操作。'
	for((i=0;i<3;i++))
	do
		echo -n ".";sleep 1
	done
	echo
}

function check_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 ]
			then
				action "$(url_list[$i])" /bin/true
		else
			action "$(url_list[$i])" /bin/false
		fi
	done
	((check_count++))
}

main(){
	while true
	do
		check_url
		echo "---------check count:${check_count}------------"
		sleep 5
	done
}
main

[root@codis-178 ~]# sh 13_5.sh
3秒后。执行检查URL操作。...
http://www.baidu.com                                       [  OK  ]
http://www.163.com                                         [  OK  ]
http://www.anzhi.com                                       [  OK  ]
---------check count:1------------
3秒后。执行检查URL操作。...
http://www.baidu.com                                       [  OK  ]
http://www.163.com                                         [  OK  ]
http://www.anzhi.com                                       [  OK  ]
---------check count:2------------
3秒后。执行检查URL操作。...
http://www.baidu.com                                       [  OK  ]
http://www.163.com                                         [  OK  ]
http://www.anzhi.com                                       [  OK  ]
---------check count:3------------
3秒后。执行检查URL操作。...
http://www.baidu.com                                       [  OK  ]
http://www.163.com                                         [  OK  ]
http://www.anzhi.com                                       [  OK  ]

(3)开发一个每30秒监控MySQL主从复制是否异常的脚本

[root@codis-178 ~]# cat 13_6.sh
#!/bin/bash
#######################################
# this script function is:
# check_mysql_slave_replication_status
# USER     YYYY-MM-DD - ACTION
# xiaoda   2017-08-30 - Created
######################################
path=/server/scripts
MAIL_GROUP="xiaoda@163.com xiao@163.com"
PAGER_GROUP="13929087438 18753928455"
LOG_FILE="/tmp/web_check.log"
USER=root
PASSWORD=123456
PORT=3306
MYSQLCMD="mysql -u$USER -p$PASSWORD -S /data/$PORT/mysql.sock"

error=(1008 1007 1062)
RETVAL=0
[ ! -d "$path" ] $$ mkdir -p $path

function JudgeError(){
	for(( i=0; i<${#error[*]}; i++))
	do
		if [ "$1" == "${error[$i]}" ]
			then
				echo "MySQL slave error is $1,auto repairing it."
				$MYSQLCMD -e "stop slave;set global sql_slave_skip_counter=1;start slave;"
		fi
	done
	return $1
}

function CheckDb(){
	status=($|awk -F ':' '/_Running|Last_Error|_Behind/{print $NF}' slave.log)
	expr ${status[3]} + 1 &>/dev/null
	if [ $? -ne 0 ];then
		status[3]=300
	fi
	if [ "${status[0]}" == "Yes" -a "${status[1]}" == "Yes" -a ${status[3]} -lt 120 ]
		then
			return 0
	else
		JudgeError ${status[2]}
	fi
}

function MAIL(){
	local SUBJECT_CONTENT=$1
	for MAIL_USER in `echo $MAIL_FROUP`
	do
		mail -s "$SUBJECT_CONTENT " $MAIL_USER <$LOG_FILE
	done
}

function PAGER(){
	for PAGER_USER in `echo $PAGER_GROUP`
	do
		TITLE=$1
		CONTACT=$PAGER_USER
		HTTPGW=http://oldboy.sms.cn
		curl -d cdkey=5ADF-EFA -d password=123 -d phone=$CONTACT -d message="$TITLE[$2]"
	done
}

function SendMsg(){
	if [ $1 -ne 0 ]
		then
			RETVAL=1
			NOW_TIME=`date +"%Y-%M-%d %H:%M:%S"`
			SUBJECT_CONTENT="mysql slave is error, error is $2,${NOW_TIME}."
			echo -e "$SUBJECT_CONTENT"|tee $LOG_FILE
			MAIL $SUBJECT_CONTENT $NOW_TIME
	else
		echo "Mysql slave status is ok"
		RETVAL=0
	fi
	return $RETVAL
}
function main(){
	while true
	do
		CheckDb
		SendMsg
		sleep 30
	done
}
main

三、运维必会的脚本

1.系统及各类服务监控脚本(文件、内存、磁盘、端口、URL)
2.文件篡改,篡改恢复脚本
3.各类服务Rsync、Nginx、MySQL等启停脚本
4.MySQL主从复制监控及自动恢复脚本
5.一键配置MySQL多实例及主从的脚本
6.监控HTTP、MySQL、Rsync、NFS、Memcached等服务脚本
7.一键安装LNMP、一键优化Linux系统、一键安装数据库及优化等脚本
8.MySQL分库、分表、自动备份脚本
9.根据网络连接数及Web日志PV数封IP脚本
10.监控网站的PV及流量
11.检查Web服务器多个URL地址脚本
12.批量创建用户及设置随机密码脚本

VIM编辑器的优化

vim /etc/vimrc
#关闭兼容模式
set nocompatible
#设置历史记录步数
set history=100
#开启相关插件
filetype on
filetype plugin on
filetype indent on
#当文件在外部被修改时自动更新文件
set autoread
#激活鼠标的使用
set mouse=a
#开启语法
stntax enable
#高亮显示当前行
set cursorline
hi cursorline guibg=#00ff00
hi CursorColumn guibg=#00ff00
set nofen
set fdl=0
#使用空格来替换Tab
set expandtab
#设置所有的Tab和缩进为4个空格
set tabstop=4
#设置<<和>>命令移动时的宽度为4
set shiftwidth=4
#使得按退格键时可以一次删掉4个空格
set softtabstop=4
set smarttab
#自动缩进
set ai
#智能缩进
set si
#自动换行
set wrap
#设置软宽度
set sw=4
set wildmenu
#显示标尺
set ruler
#设置命令行的高度
set cmdheight=1
#显示行数
set lz
#设置退格
set backspace=col,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
#设置高亮
highlight Search ctermbg=black ctermfg=white guifg=white guibg=black
#自动增加解释器及作者版本等信息
autocmd BufNewFile *.sh exec ";call SetTitle()"
func SetTitle()
    if expand("%:e") == 'sh'
        call setline(1, "#!/bin/bash")
        call setline(2, "#Author:xiaoda")
        call setline(3, "#Time:".strftime("%F %T"))
        call setline(4, "#Name:".expand("%"))
        call setline(5, "#Version:V1.0")
        call setline(6, "#Description:This is a test script")
    endif
endfunc
posted @ 2017-08-30 18:12  BXBZ—边学边做  阅读(216)  评论(0编辑  收藏  举报