Shell脚本之for语句

  • 遍历
1:
[root@master shell]# cat for_1.sh 
#!/bin/bash

for n in A B C D E F G
do
    echo "The next letter is $n"
done 
[root@master shell]# sh for_1.sh 
The next letter is A
The next letter is B
The next letter is C
The next letter is D
The next letter is E
The next letter is F
The next letter is G
  • 后面追加字符,前面要有空格,这样遍历才能区分开
1:
[root@master shell]# cat for_2.sh 
#!/bin/bash

list="A B C D E F"
list=$list" G"
for n in $list
do
    echo "The next letter is $n"
done 
[root@master shell]# sh for_2.sh 
The next letter is A
The next letter is B
The next letter is C
The next letter is D
The next letter is E
The next letter is F
The next letter is G
  • for循环查看在终端执行后的结果
1:
[root@master shell]# cat for_3.sh 
#!/bin/bash
for state in `ls /root`
do
    echo "Have you ever visited $state?"
done
[root@master shell]# sh for_3.sh 
Have you ever visited admin-openrc?
Have you ever visited anaconda-ks.cfg?
Have you ever visited demo-openrc?
Have you ever visited python?
Have you ever visited rhel-server-7.2-x86_64-dvd.iso?
  • for循环遍历文件
1:
[root@master shell]# cat for_4.sh
#!/bin/bash

for file in /mnt/*
do
    if [ -d "$file" ];then 
    echo "$file is a directory"
    elif [ -f "$file" ];then
    echo "$file is a file"
    fi
done
[root@master shell]# sh for_4.sh
/mnt/file1 is a file
/mnt/file10 is a file
/mnt/file2 is a file
/mnt/file3 is a file
/mnt/file4 is a file
/mnt/file5 is a file
/mnt/file6 is a file
/mnt/file7 is a file
/mnt/file8 is a file
/mnt/file9 is a file
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值