if语句、for语句练习

单分支之if语句

语法:

if测试条件1;then

arg1

else

arg2

fi

多分支if语句

 

语法:

if 测试条件1 ;then

arg1

elif 测试条件2 ;then

arg2

elif 测试条件3 ;then

arg3

else

arg4

fi

for语句

语法:

for i in 参数列表 ;do

循环体

done

参数列表:

{1..100}

`seq [起始数[步进]] 结束数`

练习

实例1、求和1到100

#!/bin/bash

let sum=0

for I in {1..100} ;do

let sum=$[ sum+I ]

done

echo “$sum

实例2 取出/etc/passwd的用户,并向每个用户说hello

#!/bin/bash

LINE=`wc -l /etc/passwd | cut -d” ” -f1`

for i in `seq 1 $LINE` ;do

echo “hello `head -n$i /etc/passwd | tail -n1 | cut -d: -f1`”

done

实例3 组合使用for,if语句。批量创建用户并设定密码

#!/bin/bash

for I in {1..10}; do

if id cxin$I &> /dev/null ;then

echo”cxin$I is ext.”

else

useradd cxin$I

echo cxin$I | passwd –stdin cxin$I &>/dev/null

echo “add cxin$I success”

fi

done

实例4 批量删除用户,先判断用户是否存在,若存在就删除并提示删除成功;若不存在,则提示用户不存在

#!/bin/bash

for I in {1..10} ;do

if id xin$I &> /dev/null ;then

echo xin$I is ext,you can del it.

userdel xin$I

echo del xin$I success

else

echo xin$I not ext

fi

done

 

实例5 根据参数add、del来确定下一步操作.如果是add,则添加用户;如果是del,则删除用户

#!/bin/bash

if [ $1 == add ] &> /dev/null ;then

for I in {1..10} ;do

useradd chenx$I

echo add chenx$I success

echo chenx$I | passwd –stdin chenx$ &> /dev/null

done

else

[ $1 == del ] &> /dev/null

for I in {1..10} ;do

userdel -r chenx$I

echo del chenx$I success

done

fi

本文来自投稿,不代表Linux运维部落立场,如若转载,请注明出处:http://www.178linux.com/96227

(0)
chenxinchenxin
上一篇 2018-04-15 21:48
下一篇 2018-04-15 22:39

相关推荐