建站优化

当前位置:

shell脚本for循环

浏览量:61次

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

[声明]本网转载网络媒体稿件是为了传播更多的信息,此类稿件不代表本网观点,本网不承担此类稿件侵权行为的连带责任。故此,如果您发现本网站的内容侵犯了您的版权,请您的相关内容发至此邮箱【779898168@qq.com】,我们在确认后,会立即删除,保证您的版权。