shell基础脚本

本文介绍了Shell脚本的基础操作,包括在/backup目录下创建和管理.txt文件,批量修改文件扩展名,打包压缩文件,使用for循环进行文件操作。此外,还讲解了Shell中的字符串处理,变量运算,awk和bc等工具进行数学计算,以及编写类似计算器的脚本。最后,讨论了Shell中的条件判断语句如if-else,文件比较以及服务状态检测。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在/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

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 “ n u m 1 + num1+ num1+num2= [ [ [num1+ n u m 2 ] " e c h o " num2]" echo " num2]"echo"num1- n u m 2 = num2= num2=[ n u m 1 − num1- num1num2]”
echo “ n u m 1 ∗ num1* num1num2= [ [ [num1* n u m 2 ] " e c h o " num2]" echo " num2]"echo"num1/ n u m 2 = num2= num2=[ n u m 1 / num1/ 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,KaTeX parse error: Expected 'EOF', got '}' at position 2: 5}̲') Kernel=(hostnamectl |awk '/Kernel/{print KaTeX parse error: Expected 'EOF', got '}' at position 3: NF}̲') Vm=(hostnamectl |awk '/Virtua/{print KaTeX parse error: Expected 'EOF', got '}' at position 3: NF}̲') Sh=(hostnamectl |awk '/Static/{print KaTeX parse error: Expected 'EOF', got '}' at position 3: NF}̲') Eth0=(ifconfig eth0 |awk 'NR2{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲') Lo=(ifconfig lo |awk 'NR2{print KaTeX parse error: Expected 'EOF', got '}' at position 2: 2}̲') W_network=(curl -s ifconfig.me)
echo “当前系统的版本为: S y s t e m " e c h o " 当 前 系 统 内 核 版 本 为 : System" echo "当前系统内核版本为: System"echo"Kernel”
echo “当前系统虚拟化平台为: V m " e c h o " 当 前 系 统 静 态 主 机 名 为 : Vm" echo "当前系统静态主机名为: Vm"echo"Sh”
echo “当前系统eth0ip地址为: E t h 0 " e c h o " 当 前 系 统 l o i p 地 址 为 : Eth0" echo "当前系统loip地址为: Eth0"echo"loipLo”
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

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 KaTeX parse error: Expected 'EOF', got '#' at position 7: M_Dir #̲要求用户输入指定要备份的数据库…M_user -p$M_pass -B D b > Db > Db>M_Dir/ D a t e − {Date}- 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 KaTeX parse error: Expected 'EOF', got '#' at position 7: M_Dir #̲要求用户输入指定要备份的数据库…M_user -p$M_pass -B D b > Db > Db>M_Dir/ D a t e − {Date}- 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 KaTeX parse error: Expected 'EOF', got '&' at position 6: ser &̲>/dev/null #根据上…?
if [ $rc -eq 0 ];then
echo “该服务 $ser 正在运行…”
elif [ $rc -eq 4 ];then
echo “系统中没有该服务 s e r " e l s e e c h o " 该 服 务 ser" else echo "该服务 ser"elseecho"ser 没有在运行…”
fi

位置变量传参

[root@shell shell]# cat server.sh
#!/bin/bash
#根据用户输入的服务进行检测服务状态
systemctl status KaTeX parse error: Expected 'EOF', got '&' at position 4: 1 &̲>/dev/null #根据上…?
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

不一样的我

原创:蘑菇有毒
来来回回千百遍
小爷我也是很疲倦
yf
一起玩耍呀

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值