for命令linux,linux中的for命令

bash shell提供了for命令,用于创建通过一系列值重复的循环。每次重复使用系列中的一个值执行一个定义的命令集。

for命令基本格式为:

for var in list

do

commands

done1.读取列表中的值

#!/bin/bash

#basic for command

for test in a b c d e f

do

echo The next state is $test

done

每次for命令通过提供的值列表进行矢代时,它将列表中想下个值赋值给变量

[root@localhost ~]# ./test1.sh

The next state is a

The next state is b

The next state is c

The next state is d

The next state is e

The next state is f2.读取列表中的复杂值

#!/bin/bash

for test in i don\'t know

do

echo "Word:$test"

done

注意:分号(')这里需要加斜杠(\)进行转义

[root@localhost ~]# ./test2.sh

Word:i

Word:don't

Word:know3.从变量读取列表

#!/bin/bash

list="a b c d "

for state in $list

do

echo "Have you ever visited $state?"

done

[root@localhost ~]# ./test4.sh

Have you ever visited a?

Have you ever visited b?

Have you ever visited c?

Have you ever visited d?

4.读取命令中的值

生成列表中使用的另一个方法是使用命令输出,可以使用反引号字符来执行生成输出的任何命令,然后在for命令中使用命令输出:

新建一个states文件,并且添加数据内容

[root@localhost ~]# cat states

ak

bn

cd

dr

#!/bin/bash

file="states"

for state in `cat $file`

do

echo "Visit beautiful $state"

done

[root@localhost ~]# ./test5.sh

Visit beautiful ak

Visit beautiful bn

Visit beautiful cd

Visit beautiful dr

5.改变字段分隔符

内部字段分隔符(IFS),bash shell将以下字符看作是字段分隔符

空格

制表符

换行符

#!/bin/bash

file="states"

IFS=$'\n'

for state in `cat $file`

do

echo "Visit beautiful $state"

done

IFS=$'\n'通知bash shell在数值中忽略空格和制表符

6.使用通配符读取目录

#!/bin/bash

for file in /home/l*

do

if [ -d "$file" ]

then

echo "$file is a directory"

elif [ -f "$file" ]

then

echo "$file is a file"

fi

done

[root@localhost ~]# ./test6.sh

/home/ley is a directory

for命令失代/home/ley列表的结果,然后用test命令查看是目录(-d)还是文件(-f)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值