for命令

重复执行一系列命令在编程中很常见。通常你需要重复一组命令直至达到某个特定条件,比如处理某个目录下的所有文件、系统上的所有用户或是某个文本文件中的所有行。

bash shell提供了for命令,允许你创建一个遍历一系列值的循环。每个迭代都通过一个该系类中的值执行一组预定义的命令。

for 语法:

for var in list

do

commands

done

实例1:for遍历目录

for file in /root/*
do
  if [ -d "$file" ]
  then
     echo "$file is a directory"
  elif [ -f "$file" ]
  then
     echo "$file is a file"
  else
     echo "$file doesn't exist"
  fi
done

输出结果为:

/root/1 is a file
/root/anaconda-ks.cfg is a file
/root/cash.sh is a file
/root/chown.sh is a file
/root/Desktop is a directory
/root/evalre.sh is a file
/root/evalsource is a file
/root/format.sh is a file
/root/for.sh is a file
/root/group.sh is a file
/root/hfile is a file
/root/hoststatus.txt is a file
/root/if.sh is a file
/root/install.log is a file
/root/install.log.syslog is a file
/root/iplist is a file
/root/iptest.sh is a file
/root/ntfs-3g_ntfsprogs-2013.1.13 is a directory

心得:for语句可以使用文件扩展匹配来遍历通配符生成的文件列表,然后它会遍历列表中的下一个文件。可以将任意多的通配符放进列表中。

实例2:用for循环实现批量修改文件名

1、创建脚本实验数据
[root@localhost ~]# cd /home/centos/
[root@localhost centos]# touch abc_12345_1_.centos.jpg  abc_12345_2_centos.jpg  abc_12345_3_centos.jpg  abc_12345_4_centos.jpg  abc_12345_5_centos.jpg
2、用for循环遍历所有.jpg的文件,去除.jpg文件名中centos字符
#!/bin/bash
for file in `ls ./*.jpg` ;do
mv $file `echo $file|sed 's/centos//g'`
done

输出结果为:

[root@localhost centos]# ls
abc_12345_1_..jpg  abc_12345_2_.jpg  abc_12345_3_.jpg  abc_12345_4_.jpg  abc_12345_5_.jpg

心得:shell脚本for循环结合sed可以批量更改文件名