shell編程示例

1. 判斷登陸用戶是否是root

is_root.sh

#!/bin/bash
# 通過環境變量判斷
test=$(env | grep 'USER' | cut -d "=" -f 2)

if [ "$test" == "root" ]
	then
	echo "Current user is root."
else
	echo "Not root."
fi

注意:給腳本賦予執行權限,如 chmod 755 is_root.sh
在這裏插入圖片描述

2. 判斷Apache 是否開啓,若未開啓則開啓

judge_apache.sh

#!/bin/bash
# 通過進程查看apache
test=$(ps aux | grep httpd | grep -v grep)

if [ -n "$test" ]
	then
		echo "Apache is running."
	else
		echo "Starting apache..."
		/etc/rc.d/init.d/httpd start &> /dev/null
		echo "done"
fi

在這裏插入圖片描述

3. 兩位加、減、乘、除計算器

calculator.sh

#!/bin/bash

# 獲取輸入數
read -p "input n1: " n1
read -p "input ope: " ope
read -p "input n2: " n2

# 三個輸入數都不爲空
if [ -n "$n1" -a -n "$n2" -a -n "$ope" ]
	then
		# 判斷兩個數是否都是數字
		test1=$( echo $n1 | sed 's/[0-9]//g' )
		test2=$( echo $n2 | sed 's/[0-9]//g' )
		
		if [ -z "$test1" -a -z "$test2" ]
			then
				if [ "$ope" == '+' ]
					then
						result=$(( $n1 + $n2 ))
				elif [ "$ope" == '-' ]
					then
						result=$(( $n1 - $n2 ))
				elif [ "$ope" == '*' ]
					then
						result=$(( $n1 * $n2 ))
				elif [ "$ope" == '/' ]
					then
						if [ "$n2" != 0 ]
							then
								result=$(( $n1 / $n2 ))
						else
							echo "In / n2 can't be 0."
							exit 1
						fi
				else
					echo "Can't recognized ope=$ope"
					exit 2
				fi
		else
			echo "Ensure n1 and n2 are number."
			exit 3
		fi

else
	echo "Input is empty."
	exit 4
fi

echo "$n1 $ope $n2 = $result"

在這裏插入圖片描述

4. case 示例

choose.sh

#!/bin/bash

read -p "Input: " cho

case $cho in
	"yes")
		echo "Your choose is yes!"
		;;
	"no")
		echo "Your choose is no!"
		;;
	*)
		echo "Error!"
		;;
esac

在這裏插入圖片描述

完!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章