美文网首页
shell的for循环

shell的for循环

作者: 水平号 | 来源:发表于2020-03-05 17:19 被阅读0次

最佳推荐
While 适合文件逐行处理
For 固定循环
While until不固定循环(需要满足条件退出)

For 循环默认以空格为分隔符
for循环: 将读入的内容以IFS(shell中的环境变量,Internal Field Seperator,字段分隔符)为界分隔,然后将各个分隔开的内容,逐一读入变量line。本质上说,for循环读取的是字段,只不过可以设置IFS为\n这样能够逐行读取。

*while循环:会将每行的内容读入到line变量*

如果希望for处理文件按回车分隔,则需重新定义分隔符
IFS:内部字段分隔符
IFS=$'\n'

for循环的特性

只要有值赋给i,就进行循环,有几个值就循环几次。
但循环体调用或不调用被赋值后的i, 都不会影响循环体里面的执行。
for i in 1 2 3
do
echo "test"
done

示例:新建用户

#!/usr/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默认使用空格为分隔符,for不太适合处理文件,while循环更适合处理文件
#如果希望for 处理文件按回车分隔,而不是按空格或tab空格
#重新定义分隔符
#IFS内部字段分隔符
#IFS=$'\n'

IFS='
'
##for循环
for line in $(cat $1)
do
        if [ ${#line} -eq 0 ];then                   #for遇到空行会停止运行脚本(认为脚本已处理完成),所以需要判 
                                                                #断空行,遇到空行继续把脚本执行下去。
                contiune
        fi
        user1=`echo "$line" |awk '{print $1}'`
        pass=`echo "$line" |awk '{print $2}'`

        echo $user1 |xargs id &>/dev/null

        if [ $? -eq 0 ];then
                echo "user $user1 already exists"
        else
                useradd $user1
                echo "$pass" |passwd --stdin $user1 &>/dev/null
                if [ $? -eq 0 ];then
                        echo "$user1 is created."
                fi
        fi
done
##另一种 while循环
#IFS=$'\n'                while不需要重置IFS,默认可以按行处理。

 while read line
do
        user1=`echo "$line" |awk '{print $1}'`
        pass=`echo "$line" |awk '{print $2}'`

        echo $user1 |xargs id &>/dev/null
        if [ $? -eq 0 ];then
                echo "user $user1 already exists"
        else
                useradd $user1
                echo "$pass" |passwd --stdin $user1 &>/dev/null
                if [ $? -eq 0 ];then
                        echo "$user1 is created."
                fi
        fi
done < "$1"

相关文章

  • Linux Shell:Shell循环语句

    摘要:Linux,Shell Shell中常用循环有for,while Shell循环语法结构 (1)for循环语...

  • shell循环

    接上一篇shell运算符接着往下说,shell循环: shell循环有三种,一种是for循环,一种是while循环...

  • linux中批量解压.gz压缩文件

    利用for循环,注意shell中for循环写法与R不同

  • shell的for循环

    最佳推荐While 适合文件逐行处理For 固定循环While until不固定循环(需要满足条件退出) For...

  • Shell for循环

    for循环的基本语法 for 循环变量的内容语法如下 for 循环命令替换的语法如下: for循环还有三项表达式语...

  • Shell循环

    1、查询结果 2、循环数组 3、while循环 4、for循环数字

  • Shell循环

    Bash Shell中有三种循环方式:for / while / util for 循环 语法结构 : 详细示例:...

  • shell循环

    字符串长度 字符串分割 只读readonly 清除变量的值 键盘获得变量值 加减乘除运算 text 测试语句 逻辑...

  • shell ——for in 循环

    -------for in 格式------- for 无$变量 in 字符串do$变量done 参考:http:...

  • Shell for循环

    与其他编程语言类似,Shell支持for循环。 for循环一般格式为: for 变量 in 列表 列表是一组值(数...

网友评论

      本文标题:shell的for循环

      本文链接:https://www.haomeiwen.com/subject/nwpwlhtx.html