shell脚本-条件和循环
2018-01-11 本文已影响0人
其实我很dou
一. 条件
1. 判断用户是不是root
#!/bin/bash
test=$(env | grep USER | cut -d "=" -f 2)
if [ "$test" == "root" ]; then
echo current login user is root
fi
if [ "$test" == "root" ]
then
echo i am root
fi
2. 判断磁盘容量大小
#!/bin/bash
rate=`df -h | grep "sdb1" | awk '{print $5}' | cut -d "%" -f 1`
echo $rate
if [ $rate -ge 4 ]
then
echo / if full
fi
3. 判断是不是目录
#!/bin/bash
read -t 30 -p "please input a dir: " dir
if [ -d "$dir" ]
then
echo "$dir is dir";
else
echo "no no no"
fi
4. 判断httpd运行状态, 如果stop, 则start
#!/bin/bash
test=`ps -ef | grep httpd | grep -v grep`
if [ -n "$test" ]
then
echo "httpd is start"
else
echo 'httpd is stop'
/etc/init.d/httpd start
fi
5. shell计算器
#!/bin/bash
read -t 30 -p 'please input first num: ' num1
read -t 30 -p 'please input second num: ' num2
read -t 30 -p 'please input operator: ' ope
sum=''
if [ -n "$num1" -a -n "$num2" -a -n "$ope" ]
then
# 判断是不是数值
test1=`echo $num1 | sed 's/[0-9]//g'`
test2=`echo $num2 | sed 's/[0-9]//g'`
if [ -n "$test1" -o -n "$test2" ]
then
echo "invalid number"
exit 11
else
if [ "$ope" == "+" ]
then
sum=$(($num1 + $num2))
elif [ "$ope" == "-" ]
then
sum=$(($num1 - $num2))
elif [ "$ope" == "*" ]
then
sum=$(($num1 * $num2))
elif [ "$ope" == "/" ]
then
sum=$(($num1 / $num2))
else
echo "invalid operator"
exit 12
fi
fi
else
echo "invilid number or operator"
exit 10
fi
if [ -n "$sum" ]
then
echo "$num1 $ope $num2 = $sum"
fi
6. case练习
#!/bin/bash
read -t 30 -p "are you sure [y|n] : " choose
case "$choose" in
# 正则匹配
Y|y|[Y|y])
echo "yes"
;;
"n")
echo "no"
;;
*)
echo "other"
;;
esac
二. 循环
1. 批量解压缩
#!/bin/bash
cd /root/tar
echo $?;
ls *.tar.gz > ls.log
ls *.tgz >> ls.log
files=`cat ls.log`
echo $files
for file in $files
do
tar -zxf $file &> /dev/null
done
rm -rf ls.log
2. 求和
#!/bin/bash
s=0;
for(( i=1; i<=100; i=i+1))
do
s=$(( $s + $i))
done
echo $s
3. 批量添加用户, 并赋予初始密码
#!/bin/bash
read -t 30 -p "please input username-prefix: " user
read -t 30 -p "please input count: " count
read -t 30 -p "please passwd: " passwd
if [ -z "$user" -o -z "$count" -o -z "$passwd" ]
then
echo "invalid param"
exit 13
fi
test_count=`echo $count | sed 's/[0-9]//g'`
if [ -z "$test_count" ]
then
# 添加用户
for(( i=1;i<=$count;i=i+1 ))
do
/usr/sbin/useradd $user$i &> /dev/null
echo $passwd | /usr/bin/passwd --stdin $name$i &> /dev/null
done
fi
4. 批量删除用户
#!/bin/bash
users=$( cat /etc/passwd | grep adduser | cut -d ":" -f 1 )
#users=`cat /etc/passwd | grep /bin/bash | grep -v root`
for user in $users
do
/usr/sbin/userdel -r $user
done
5. while循环
#!/bin/bash
# 求两个数的累加和
read -t 30 -p "please start num: " start_num
read -t 30 -p "please end num: " end_num
sum=0
while [ $start_num -le $end_num ]
do
sum=$(( $start_num + $sum ))
start_num=$(( $start_num + 1 ))
done
echo $sum