shell 变量

在/backup下创建10个.txt的文件,找到/backup目录下所有后缀名为.txt的文件
1)批量修改txt为txt.bak                        
2)把所有的.bak文件打包压缩为123.tar.gz        
3)批量还原文件的名字,及把增加的.bak再删除

[root@shell shell]# vim  mv.sh
#!/bin/bash
Dir=/backup
#判断目录是否存在,不存在则创建
[ -d $Dir ] || mkdir -p  $Dir
#创建10个文件
touch  $Dir/{1..10}.txt
#找到这些文件,进行批量修改名称
find $Dir -type f -name "*.txt" >$Dir/txt.log
#批量修改文件名
sed -r 's#(.*)#mv \1 \1.bak#g'  $Dir/txt.log |bash
#打包压缩为123.tar.gz
tar czf  $Dir/123.tar.gz  $Dir/*.bak
#批量进行还原文件名
find $Dir -type f -name "*.bak" >$Dir/bak.log
#还原
sed -r 's#(.*).bak#mv \1.bak \1#g'  $Dir/bak.log |bash 
for循环方式修改
[root@shell shell]# vim  for_name.sh
#!/bin/bash
Dir=/backup
#判断目录是否存在,不存在则创建
[ -d $Dir ] || mkdir -p  $Dir
#创建10个文件
touch  $Dir/{1..10}.txt
#批量修改文件名
find $Dir -type f -name "*.txt" >$Dir/txt.log
#使用for循环进行修改
for i in $(cat $Dir/txt.log)
do
    mv $i $i.bak
done
#打包压缩为123.tar.gz
tar czf  $Dir/123.tar.gz  $Dir/*.bak
#查找文件
find $Dir -type f -name "*.bak" >$Dir/bak.log
#批量还原
for j in $(cat $Dir/bak.log)
do
    mv $j ${j%.*}
done                
取出下列字符串长度小于3的单词,I am qiuzengjia teacher I am 18。
[root@shell shell]# vim  for-1.sh
#!/bin/bash
#定义变量
length='I am qiuzengjia teacher I am 18'
#使用for循环判断变量值长度,小于3则显示,否则不显示
for i in $length
do
    [ ${#i} -lt 3 ] && echo $i                                                                                                       
done



[root@shell shell]# echo "I am qiuzengjia teacher I am 18" |xargs -n1 |awk  '{ if ( length < 3 ) print }'
I
am
I
am
18
shell变量运算
加减乘除余方

整数运算

expr	值两边必须要有空格隔开

[root@shell shell]# expr  1 + 1
2
[root@shell shell]# num1=10
[root@shell shell]# num2=20
[root@shell shell]# expr $num1 + $num2
30
[root@shell shell]# expr $num1 - $num2
-10
[root@shell shell]# expr $num1 * $num2
expr: syntax error
[root@shell shell]# expr $num1 \* $num2
200
[root@shell shell]# expr $num1 / $num2
0
[root@shell shell]# expr $num2 / $num2
1
[root@shell shell]# expr $num2 % $num2
0
[root@shell shell]# expr $num1 % $num2
10

$(())  

[root@shell shell]# echo  $(( $num1 + $num2 ))
30
[root@shell shell]# echo  $(( $num1 - $num2 ))
-10
[root@shell shell]# echo  $(( $num1 * $num2 ))
200

$[]

[root@shell shell]# echo $[$num1 * $num2 ]
200
[root@shell shell]# echo $[$num1 / $num2 ]
0
[root@shell shell]# echo $[$num1 + $num2 ]
30



let		****

[root@shell shell]# a=1
[root@shell shell]# let a++
[root@shell shell]# echo $a
2
[root@shell shell]# let a++
[root@shell shell]# echo $a
3
[root@shell shell]# let a--
[root@shell shell]# echo $a
2

小数运算

bc   awk   python 

bc
[root@shell shell]# yum install  -y  bc

[root@shell shell]# echo  $num1 + $num2 |bc
30
[root@shell shell]# bc
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
10+20
30
^C
(interrupt) Exiting bc.
[root@shell shell]# echo  $num1 - $num2 |bc
-10
[root@shell shell]# echo  $num1 ^ $num2 |bc
100000000000000000000
[root@shell shell]# echo  $num1 / $num2 |bc
0
[root@shell shell]# echo  "scale=2;$num1 / $num2" | bc
.50
[root@shell shell]# echo  "scale=1;$num1 / $num2" | bc
.5
[root@shell shell]# echo  "scale=1; 20 / 6" | bc
3.3
[root@shell shell]# 



awk

[root@shell shell]# awk  'BEGIN{print 20 * 10 }'
200
[root@shell shell]# awk  'BEGIN{print 20 ^ 10 }'
10240000000000
[root@shell shell]# awk  'BEGIN{print 20 / 6 }'
3.33333
[root@shell shell]# awk  'BEGIN{printf  "%.2f\n", 20 / 6 }'
3.33

python

[root@shell shell]# echo  "print $num1+$num2" | python
30
[root@shell shell]# echo  "print $num1/$num2" | python
0
[root@shell shell]# echo  "print ${num1}.0/$num2" | python
0.5

[root@shell shell]# python
Python 2.7.5 (default, Oct 30 2018, 23:45:53) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

> > > 10+20
> > > 30
> > > 30.0/9
> > > 3.3333333333333335
示例: 执行ps aux 进行计算VSZ这列的所有数的和
[root@shell shell]# ps aux | awk 'NR>1{print $5}' |tr "\n"  "+" |sed -r 's#(.*)\+#\1\n#g' |bc
4431300

[root@shell shell]# ps aux | awk 'NR>1{print $5}' |tr "\n"  "+" |sed -r 's#(.*)\+#\1\n#g' |bc
4301596
[root@shell shell]# ps aux | awk 'NR>1{print $5}' |awk '{i+=$1}END{print i}'
4306700

[root@shell shell]# seq 100| awk '{print $1}' |tr "\n"  "+" |sed -r 's#(.*)\+#\1\n#g' |bc
5050
[root@shell shell]# seq 100| awk '{print $1}' |awk '{i+=$1}END{print i}'
5050
类似计算器的脚本
请用户输入第一个数字:10

请用户输入第二个数字:20

计算加减乘除的值全部显示出来

显示结果为
10+20=30

[root@shell shell]# vim  csl.sh
#!/bin/bash
read -p "请输入一个数字:" num1
read -p "请输入二个数字:" num2
echo "$num1+$num2=$[$num1+$num2]"
echo "$num1-$num2=$[$num1-$num2]"   
echo "$num1*$num2=$[$num1*$num2]"
echo "$num1/$num2=$[$num1/$num2]"
shell变量案例
使用Shell脚本打印,系统版本、内核版本平台、虚拟平台、静态主机名、eth0网卡IP地址、lo网卡IP地址、当前主机的外网IP地址curl -s  icanhazip.com

[root@shell shell]# cat  varable.sh
#!/bin/bash
System=$(hostnamectl |awk  '/System/{print $3,$4,$5}')
Kernel=$(hostnamectl |awk  '/Kernel/{print $NF}')
Vm=$(hostnamectl |awk  '/Virtua/{print $NF}')
Sh=$(hostnamectl |awk  '/Static/{print $NF}')
Eth0=$(ifconfig eth0 |awk 'NR==2{print $2}')
Lo=$(ifconfig lo |awk 'NR==2{print $2}')
W_network=$(curl -s ifconfig.me)
echo "当前系统的版本为:$System"
echo "当前系统内核版本为:$Kernel"
echo "当前系统虚拟化平台为:$Vm"
echo "当前系统静态主机名为:$Sh"
echo "当前系统eth0ip地址为:$Eth0"
echo "当前系统loip地址为:$Lo"
echo "当前系统外网ip地址为:$W_network"

需求描述:变量string="Bigdata process is Hadoop, Hadoop is open source project",执行脚本后,打印输出string变量,并给出用户以下选项:

#需求
1)打印string长度
2)删除字符串中所有的Hadoop
3)替换第一个Hadoop为Linux
4)替换全部Hadoop为Linux
用户请输入数字1|2|3|4,可以执行对应项的功能。
[root@shell shell]# cat string.sh
#!/bin/bash
string="Bigdata process is Hadoop, Hadoop is open source project"
echo $string
cat <<EOF
1)打印string长度
2)删除字符串中所有的Hadoop
3)替换第一个Hadoop为Linux
4)替换全部Hadoop为Linux
EOF
read -p "请输入上方的数字[1|2|3|4],得到对应的功能:" num
#判断用户输入的数字进行输出结果
if [ $num -eq 1 ];then
    echo ${#string}
fi
if [ $num -eq 2 ];then
    echo ${string//Hadoop/}
fi
if [ $num -eq 3 ];then
    echo ${string/Hadoop/Linux}
fi
if [ $num -eq 4 ];then
    echo ${string//Hadoop/Linux}
fi

[root@shell shell]# cat  string.sh
#!/bin/bash
string="Bigdata process is Hadoop, Hadoop is open source project"
echo $string
cat <<EOF
1)打印string长度
2)删除字符串中所有的Hadoop
3)替换第一个Hadoop为Linux
4)替换全部Hadoop为Linux
EOF
read -p "请输入上方的数字[1|2|3|4],得到对应的功能:" num
#判断用户输入的数字进行输出结果
if [ $num -eq 1 ];then
    echo ${#string}
elif [ $num -eq 2 ];then
    echo ${string//Hadoop/}
elif [ $num -eq 3 ];then
    echo ${string/Hadoop/Linux}
elif [ $num -eq 4 ];then
    echo ${string//Hadoop/Linux}
else
    echo "你不老实!"
fi
流程控制if语句

单分支结构

if  如果你有钱  ;then 
	就嫁给你
fi 

[root@shell shell]# cat  if-1.sh
#!/bin/bash
if ls /opt ;then
    echo "Ok"
fi

双分支结构

if  如果你有钱  ;then 
	就嫁给你
else
	再见
fi 


[root@shell shell]# cat  if-1.sh
#!/bin/bash
if ls /opt ;then
    echo "Ok"
else
    echo "err"
fi

多分支

if  如果你有钱  ;then 
	就嫁给你
elif 如果你有房  ;then 
	也会嫁给你
elif  你在老男孩学运维; then
	我们可以试试
elif	活好,运维技术好 ;then
	倒贴也嫁给你
else
	再见
fi 

写个脚本判断用户是否存在系统
提示用户输入一个用户

判断是否存在该系统
判断是否存在家目录

[root@shell shell]# cat user.sh
#!/bin/bash
#请用户输入一个用户
read -p "请输入你要查询的用户:" user
#根据用户输入要查询的用户进行判断是否存在
if id $user &>/dev/null; then
    if ls /home/$user &>/dev/null;then
        echo "该用户 $user 存在该系统"
        echo "该用户存在家目录"
    else
        echo "该用户 $user 存在该系统"
        echo "该用户不存在家目录"
    fi
else
    if ls /home/$user &>/dev/null;then
        echo "该用户存在家目录"
        echo "该用户 $user 不存在该系统"
    else
        echo "该用户 $user 不存在该系统"
        echo "该用户不存在家目录"
    fi
fi


系统运维工程师
监控运维工程师
桌面运维工程师
网络运维工程师
网络安全工程师
DBA工程师
架构师
运维开发
自动化运维
if语句中的文件比较
选项	说明								示例
-e	如果文件或目录存在则为真				[ -e file ]
-s	如果文件存在且至少有一个字符则为真		[ -s file ]
-d	如果文件存在且为目录则为真				[ -d file ]
-f	如果文件存在且为普通文件则为真			[ -f file ]
-r	如果文件存在且可读则为真				[ -r file ]
-w	如果文件存在且可写则为真				[ -w file ]
-x	如果文件存在且可执行则为真				[ -x file ]


[root@shell shell]# [ -d /etc ] && echo "该目录存在"  || echo "该目录不存在"
该目录存在
[root@shell shell]# [ -d /etcc ] && echo "该目录存在"  || echo "该目录不存在"
该目录不存在
[root@shell shell]# [ -f /etcc ] && echo "该目录存在"  || echo "该目录不存在"
该目录不存在
[root@shell shell]# [ -f /etc ] && echo "该目录存在"  || echo "该目录不存在"
该目录不存在
[root@shell shell]# [ -f /etc/hosts ] && echo "该目录存在"  || echo "该目录不存在"
该目录存在
[root@shell shell]# [ ! -f /etc/hosts ] && echo "该目录存在"  || echo "该目录不存在"
该目录不存在


[root@shell shell]# cat  if-2.sh
#!/bin/bash
if [ -d /opt/ ];then
    echo "该目录存在"
else
    echo "该目录不存在"
fi
文件比较场景实践,备份数据库
#1.备份mysql,手动输入你需要备份的库名称

1)提示用户手动输入库名称:read
2)如果用户输入数据库名称,则执行mysqldump命令备份
3)备份到哪,/backup/mysql

[root@shell shell]# yum  install  -y  mariadb  mariadb-server
[root@shell shell]# systemctl  start mariadb
[root@shell shell]# mysqladmin   password '123456'

mysqldump   -uroot  -p123456   -B   test  >test.sql


[root@shell shell]# cat  mysql_bak.sh
#!/bin/bash
M_Dir=/backup/mysql
M_user=root
M_pass=123456
Date=$(date +%F)
#判断备份是否存在,如果不存在,则创建
[ -d $M_Dir ] || mkdir  -p $M_Dir
#要求用户输入指定要备份的数据库
read -p  "请输入你要备份的数据库:" Db
#根据用户输入的要备份的数据库进行备份操作
mysqldump -u$M_user -p$M_pass -B $Db >$M_Dir/${Date}-${Db}.sql
#根据上一条命令的执行结果进行判断是否成功
if [ $? -eq 0 ];then
    echo "-------------------"
    echo "数据库 $Db 备份成功"
    echo "-------------------"
else
    echo "数据库 $Db 备份失败"
fi
[root@shell shell]# cat mysql_bak.sh
#!/bin/bash
M_Dir=/backup/mysql
Date=$(date +%F)
#判断备份是否存在,如果不存在,则创建
[ -d $M_Dir ] || mkdir  -p $M_Dir
#要求用户输入指定要备份的数据库
read -p  "请输入你要备份的数据库:" Db
read -p  "请输入使用哪一个用户进行备份:" M_user
read -p  "请输入该用户的密码:" M_pass
#根据用户输入的要备份的数据库进行备份操作
mysqldump -u$M_user -p$M_pass -B $Db >$M_Dir/${Date}-${Db}.sql
#根据上一条命令的执行结果进行判断是否成功
if [ $? -eq 0 ];then
    echo "-------------------"
    echo "数据库 $Db 备份成功"
    echo "-------------------"
else
    echo "数据库 $Db 备份失败"
fi

#严谨版
[root@shell shell]# cat  mysql_bak.sh
#!/bin/bash
M_Dir=/backup/mysql
Date=$(date +%F)
#判断备份是否存在,如果不存在,则创建
[ -d $M_Dir ] || mkdir  -p $M_Dir
#要求用户输入指定要备份的数据库
read -p  "请输入你要备份的数据库:" Db
read -p  "请输入使用哪一个用户进行备份:" M_user
read -s -p  "请输入该用户的密码:" M_pass
echo
#根据用户输入的要备份的数据库进行备份操作
mysqldump -u$M_user -p$M_pass -B $Db >$M_Dir/${Date}-${Db}.sql
#根据上一条命令的执行结果进行判断是否成功
if [ $? -eq 0 ];then
    echo "-------------------"
    echo "数据库 $Db 备份成功"
    echo "-------------------"
else
    echo "数据库 $Db 备份失败"
fi




数值比较[整数1 操作符 整数2 ]
选项	说明						示例
-eq		等于则条件为真			[ 1 -eq 10 ]
-ne		不等于则条件为真		[ 1 -ne 10 ]
-gt		大于则条件为真			[ 1 -gt 10 ]
-lt		小于则条件为真			[ 1 -lt 10 ]
-ge		大于等于则条件为真		[ 1 -ge 10 ]
-le		小于等于则条件为真		[ 1 -le 10 ]



[root@shell shell]# [ 10 -eq 20 ] &&  echo "为真" || echo "为假"
为假
[root@shell shell]# [ 20 -eq 20 ] &&  echo "为真" || echo "为假"
为真
[root@shell shell]# [ 20 -ne 20 ] &&  echo "为真" || echo "为假"
为假
[root@shell shell]# [ 10 -ne 20 ] &&  echo "为真" || echo "为假"
为真
[root@shell shell]# [ 10 -ge 20 ] &&  echo "为真" || echo "为假"
为假
[root@shell shell]# [ 30 -ge 20 ] &&  echo "为真" || echo "为假"
为真
[root@shell shell]# [ 20 -ge 20 ] &&  echo "为真" || echo "为假"
为真
[root@shell shell]# [ 20 -le 20 ] &&  echo "为真" || echo "为假"
为真
[root@shell shell]# [ 30 -le 20 ] &&  echo "为真" || echo "为假"
为假
[root@shell shell]# [ 30 -gt 20 ] &&  echo "为真" || echo "为假"
为真
[root@shell shell]# [ 20 -gt 20 ] &&  echo "为真" || echo "为假"
为假
[root@shell shell]# [ 20 -lt 20 ] &&  echo "为真" || echo "为假"
为假
[root@shell shell]# [ 10 -lt 20 ] &&  echo "为真" || echo "为假"
为真



编写一个脚本,检测服务是否运行
1)如何判断我们服务是否是运行 systemctl status sshd
2)判断前者命令执行是否成功,成功则输出运行,失败则输出程序没有运行

正则运行
不在运行
没有这个服务



[root@shell shell]# cat server.sh
#!/bin/bash
#请用户输入要查看的服务名称
read -p "请输入你要查看的服务:" ser
#根据用户输入的服务进行检测服务状态
systemctl  status  $ser  &>/dev/null
#根据上条的执行结果进行判断
rc=$?
if [ $rc -eq 0 ];then
    echo "该服务 $ser 正在运行......"
elif [ $rc -eq 4 ];then
    echo "系统中没有该服务 $ser"
else
    echo "该服务$ser 没有在运行...."
fi


位置变量传参
[root@shell shell]# cat server.sh  
#!/bin/bash
#根据用户输入的服务进行检测服务状态
systemctl  status  $1  &>/dev/null
#根据上条的执行结果进行判断
rc=$?
if [ $rc -eq 0 ];then
    echo "该服务 $1 正在运行......"
elif [ $rc -eq 4 ];then
    echo "系统中没有该服务 $1"
else
    echo "该服务$1 没有在运行...."
fi


[root@shell shell]# cat  server.sh 
#!/bin/bash
#判断用户执行脚本时,必须要加一个参数
if [ $# -ne 1 ];then
    echo "脚本后面必须要跟一个参数,使用方法如下:"
    echo "Usage: $0 {sshd|network|mysql|nginx}"
    exit
fi
#根据用户输入的服务进行检测服务状态
systemctl  status  $1  &>/dev/null
#根据上条的执行结果进行判断
rc=$?
if [ $rc -eq 0 ];then
    echo "该服务 $1 正在运行......"
elif [ $rc -eq 4 ];then
    echo "系统中没有该服务 $1"
else
    echo "该服务$1 没有在运行...."
fi


场景实践二:查看磁盘/分区当前使用状态,如果使用率超过80%则报警发邮件
[root@git shell]# cat df1.sh 
#!/usr/bin/bash 
use=$(df -h |awk ' NR==2 {print $5}') 
if [ ${use/\%/} -ge 25 ];then 
         echo -e "\033[31m 磁盘使用率过高....$use \033[0m"
    else 
            echo -e "\033[32m 你的磁盘使用率正常... $use \033[0m" 
        fi 

场景实践三:条件测试,创建用户
[root@git shell]# sh user.sh
 输入一个用户www
 www 用户已存在... 
[root@git shell]# sh user.sh
 输入一个用户zhp
user.sh: line 15: [: missing `]'
[root@git shell]# !v
vim user.sh
[root@git shell]# sh user.sh
 输入一个用户xxx
 xxx 创建不存在... 
[root@git shell]# cat user.sh 
#!/bin/bash
##############################################################
# File Name: user.sh
# Time: 2019-10-17-19:46:55
# Author: qls
# Organization: www.increase93.com
##############################################################
read -p " 输入一个用户" user
 id $user &>/dev/null;
rc=$?
if [ $rc -eq 0 ]; then
    echo -e "\033[32m $user 用户已存在... \033[0m"
else
    useradd $user
    if [ $rc -eq 1 ]; then
    echo -e "\033[31m $user 已创建... \033[0m"
fi
fi

场景实践四:函数库使用,判断url地址是否能通
#!/bin/bash 
[ -f /etc/init.d/functions ] && . /etc/init.d/functions 
read -p "请输入一个网址: " url 
ping -c 1 -W 1 $url &>/dev/null 
rc=$? 
if [ $rc -eq 0 ];then 
    action "ping $url is" /bin/true 
else 
    action "ping $url is" /bin/false 
fi 
posted on 2019-10-17 21:06  酷gril  阅读(121)  评论(0编辑  收藏  举报