当前位置:首页  »  科技  »  科技百科  »  文章  »  shell脚本for循环

shell脚本for循环

来源:网络 转载:百问网 时间:2022-04-17 17:00
导读shell脚本for循环,在shell脚本中编写脚本使用for循环一般是用于判断输入的用户名是否存在,若是不存在的话那么创建该用户并设置密码,否则程序会继续提示用户,也就是提示重新输入新建用户名称。

shell脚本中的for循环是怎样的呢?下面就让我们一起来了解一下吧:

在shell脚本中编写脚本使用for循环一般是用于判断输入的用户名是否存在,若是不存在的话那么创建该用户并设置密码,否则程序会继续提示用户,也就是提示重新输入新建用户名称。

在for命令中的for i in的各种用法介绍如下

for i in “file1” “file2” “file3”

for i in /boot/*

for i in /etc/*.conf

for i in $(seq -w 10) --》等宽的01-10

for i in {1…10}

for i in $( ls )

for I in $(< file)

for i in “$@” --》取所有位置参数,可以简写为for i

需要注意的是bash shell支持C式for循环。

示例代码如下:

#!/bin/bash

j=$1

for ((i=1; i<=j; i++))

do

touch file$i && echo file $i is ok

done

$@: 所有位置变量的内容

$#: 位置变量的个数

$0: 文件名

$*: 所有位置变量的内容

for循环的一般代码格式为:

for 变量名 in 列表

do

    command1

    command2

    ...

    commandN

done

参考范例:

范例一

输入代码:

for loop in 1 2 3 4 5

do

    echo "The value is: $loop"

done

输出结果为:

The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5

范例二

若是编写脚本清空所有arp缓存记录,示例代码如下:

#!/bin/bash

for i in $(arp | tail -n +2|tr -s ' ' |cut -d' ' -f1)

do 

arp -d $i 

done

以上就是小编的分享了,希望能够帮助到大家。

声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。

标签:shell脚本  for循环  
  • 热门焦点
Top
加载中...