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

你可能感兴趣的:(linux,shell,linux,bash)