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. 两位加、减、乘、除计算器
#!/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 示例
#!/bin/bash
read -p "Input: " cho
case $cho in
"yes")
echo "Your choose is yes!"
;;
"no")
echo "Your choose is no!"
;;
*)
echo "Error!"
;;
esac