Linux shell编程之for循环

for命令基本格式:

for var in list
do 
    commands
done

用法如下:

一、直接遍历一个列表

$ cat test.sh 
#!/bin/bash

for n in 1 2 3 4 5 6
do
  echo "n=$n"
done
$ ./test.sh 
n=1
n=2
n=3
n=4
n=5
n=6
注意在列表中如果含有单引号,会把单引号包括起来的字符视为一个整体。

$ cat test.sh 
#!/bin/bash


for val in I don't know if I'm a good man
do
  echo "n=$val"
done
$ ./test.sh 
n=I
n=dont know if Im
n=a
n=good
n=man
如上所示:单引号包括的内容被当做一个整体,里面的空格不会起分隔作用。
如果确实想在列表中使用单引号,有两种方法:
(1) 使用 '\'转义单引号

$ cat test.sh 
#!/bin/bash


for val in I don\'t know if I\'m a good man
do
  echo "n=$val"
done
$ ./test.sh 
n=I
n=don't
n=know
n=if
n=I'm
n=a
n=good
n=man
(2) 使用双引号将含有单引号的字串包起来。

$ cat test.sh 
#!/bin/bash


for val in I "don't" know if "I'm" a good man
do
  echo "n=$val"
done
$ ./test.sh 
n=I
n=don't
n=know
n=if
n=I'm
n=a
n=good
n=man
如果一个字串中含有空格,要用双引号包起来。
$ cat test.sh 
#!/bin/bash


for val in I "don't  know if I'm" a good man
do
  echo "n=$val"
done
$ ./test.sh 
n=I
n=don't  know if I'm
n=a
n=good
n=man
二、从变量中读取列表
$ cat test.sh 
#!/bin/bash
list="I don't  know if I'm  a good man"


for val in $list
do
  echo "n=$val"
done
$ ./test.sh 
n=I
n=don't
n=know
n=if
n=I'm
n=a
n=good
n=man
三、读取命令中的值

$ cat test.txt
apple pear banana orange 
$ cat test.sh
#!/bin/bash


for val in `cat test.txt`
do
  echo "n=$val"
done
$ ./test.sh 
n=apple
n=pear
n=banana
n=orange

四、使用通配符读取目录

$ cat test.sh
#!/bin/bash
ifs_old=$IFS
IFS=$':'
for val in ~/*
do
   if [ -d $val ]
   then
      echo "$val is a directory"
   elif [ -f $val ]
   then
      echo "$val is a file"
   fi
done
IFS=$ifs_old
$ ./test.sh 
/home/jix/begin one day.sh is a file
/home/jix/code is a directory
/home/jix/Desktop is a directory
/home/jix/Documents is a directory
/home/jix/Downloads is a directory
/home/jix/grep.txt is a file
/home/jix/grep.txt1 is a file
/home/jix/Music is a directory
/home/jix/Pictures is a directory
/home/jix/Public is a directory
/home/jix/Templates is a directory
/home/jix/Videos is a directory
注意:for val in ~/* 中的~/*不能写为"~/*",写为"~/*"会被当做一个字符串处理,
显然没有路径为~/*的文件和文件夹,程序什么都不会输出

$ cat test.sh
#!/bin/bash
ifs_old=$IFS
IFS=$':'
for val in "~/*"
do
   if [ -d $val ]
   then
      echo "$val is a directory"
   elif [ -f $val ]
   then
      echo "$val is a file"
   fi
done

IFS=$ifs_old
$ ./test.sh 
$ 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值