shell脚本常用8例

基础的shell脚本实例

  1. 查看软件包有没有安装
#!/usr/bin/bash
read -p "please input ruanjianbao  " rj
if rpm -q $rj &>/dev/null; then
	echo "$rj is already installed"
else
	echo "$rj is not installed"
fi

2.两个数比较大小

在这里插入代码片#!/usr/bin/bash

read -p "please input the first num: " num1
read -p "please input the second num: " num2

if [[ $num1 =~ ^[0-9]+$ && $num2 =~ ^[0-9]+$ ]];then
	if [ $num1 -lt $num2 ];then
		echo "The num2 is biger than the num1"
	elif [ $num1 -eq $num2 ];then
		echo "Two number equal"
	else
		echo "The num1 is biger than the num2"
  	fi
else
	echo "please enter the correct number"
fi

unset num1 num2

3.乘法口诀表

#!/usr/bin/bash

for i in {1..9};do
for j in `seq 1 $i` ;do
	echo -en " $i * $j = $[ $i * $j ]\t"
	done
	echo
done

unset i j

4.求和

#!/usr/bin/bash

for i in {1..9};do
for j in `seq 1 $i` ;do
	echo -en " $i * $j = $[ $i * $j ]\t"
	done
	echo
done

unset i j

5.打印1-9

#!/usr/bin/bash
num=0
while [ $num -lt 10 ]
do 
	echo $num
	let num=$num+1
done

6.字符判空

#!/usr/bin/bash
num1=4
num2=5
str1=Alice
str2=" "
if [ $num1 -gt $num2 ]
then
echo num1 large than num2
else
echo num1 lower than num2
fi

if [ -z $str1 ]
then
echo str1 is empty
else
echo str is not empty
fi

if [ -z $str2 ]
then
echo str2 is empty
else
echo str is not empty
fi

7.测试输入的文件类型

#!/usr/bin/bash
read -p "input a file name:" file_name
if [ -d $file_name ];then
	echo "$file_name is a directiory"
elif [ -f $file_name ];then
	echo "$file_name is a file"
elif [ -c $file_name ];then
	echo "$file_name is a devices"
else 
	echo "$file_name is unknown file"
fi

8.自定义函数

#!/usr/bin/bash
function func(){
	echo this is function
}
func

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值