zoukankan      html  css  js  c++  java
  • (八)for语句

    (1)语法

    (2)批量ping主机

    这里有个重点就是把每次ping主机的动作放到后台运行

    #!/bin/bash
    >ip.txt
    for i in {1..254}
    do 
    	ip=192.168.111.$i
    	{
    	ping -c1 -W1 $ip &>/dev/null 
    	if [ $? -eq 0 ];then
    		echo "$ip is up!" |  tee -a ip.txt
    	fi
    	}&
    done
    wait
    echo "success"
    

    (2)用户创建

    重点:seq -w 10 会生成例如 01 02,前面使用0填充

    #!/bin/bash
    while true
    do
    	read -p "please input prefix password number[bob 123456 10]" prefix password number
    	printf "user information:
    	----------------------------------
    	user prefix:$prefix
    	user password:$password
    	user number:$number
    	----------------------------------
    	"
    	read -p "Are you sure?[y|n]" action
    	if [ "$action" = y ];then
    		break
    	fi
    done
    for i in $(seq -w $number)
    do
    	user=$prefix$i
    	id $user &>/dev/null
    	if [ $? -eq 0 ];then
    		echo "user $user is already exist!"
    	else
    		useradd $user
    		echo "$password" | passwd --stdin $user &>/dev/null
    		if [ $? -eq  0 ];then
    			echo "user $user is created!"
    		fi
    	fi
    done
    

    (3)实现文件中批量创建用户

    重点:默认for循环是根据空白或tab键进行分割,这样对文件进行for循环,例如文件内容(jack01 123) 会把这一行当成两行内容,解决方案:使用IFS变量重新定义分割符
    IFS=$' '

    #!/bin/bash
    
    if [ $# -eq 0 ];then
    	echo "Usage: $(basename $0) file"
    	exit 1
    fi 
    if [ ! -f $1 ];then
    	echo "error file!"
    	exit 2
    fi
    #希望for处理文件按回车分隔,而不是空格或tab空格
    #重新定义分割符
    #IFS=$'
    '
    IFS=$'
    '
    for line in $(cat $1)
    do
    	user=$(echo $line |awk '{print $1}')
    	pass=$(echo $line |awk '{print $2}')
    	id $user &>/dev/null
    	if [ $? -eq 0 ];then
    		echo "user $user is already exists!"
    	else
    		useradd $user &>/dev/null
    		echo "$pass" | passwd --stdin $user
    		if [ $? -eq 0 ];then
    			echo "$user is created!"
    		fi
    	fi
    done
    

    用户文件内容如下,第一列是用户名,第二列是用户密码

    jack01 123
    jack02 456
    jack03 789
    
  • 相关阅读:
    BestCoder Round #14
    poj 3400 Dropping the stones
    ZOJ1610_Count the Colors(段树/为段更新)
    cxSpreadBook 要么 cxSpreadSheet 设置文本格式
    Chromium Graphics Update in 2014(滑动)
    tomcat加载时报The web application [/dmscs] created a ThreadLocal with key of type
    08-使用for循环输出杨辉三角(循环)
    PHP中遍历stdclass object 及 json 总结[中国航天神舟十号以json形式向地面返回数据]
    MIPI CSI-2规范一——概述及层级
    练习1.16
  • 原文地址:https://www.cnblogs.com/lovelinux199075/p/8907833.html
Copyright © 2011-2022 走看看