《Shell 编程》10_for 和 select 循环语句
标签(空格分隔): Shell
文章目录
10.1 for 循环语法结构
1)变量取值型:
for 变量名 in 变量取值列表 #<== 变量名依次获取变量取值列表内容(以空格分隔),每次仅取一个
do
cmd...
done
- 在此结构中 “in 变量取值列表” 可以省略,省略时相当于 in “$@”,也就是使用 for i 就相当于使用 for i in “$@”。
2)C 语言型:
for((exp1; exp2; exp3))
do
cmd...
done
10.2 for 循环范例
例 10-1
竖向打印 5、4、3、2、1 这 5 个数字。
#!/bin/bash
#for n in 5 4 3 2 1 #<== 直接列出元素
#for n in {5..1} #<== 利用大括号 {} 生成数字序列
for n in `seq 5 -1 1` #<== 采用 seq 生成数字序列
do
echo "$n"
done
例 10-2
获取当前目录下的目录或文件名,并将其作为变量列表打印输出。
#!/bin/bash
for filename in `ls`
do
echo "$filename"
done
例 10-3
用 for 循环批量修改文件扩展名。
[root@web001 scripts]# ll test/
total 0
-rw-r--r-- 1 root root 0 Oct 26 12:47 test.gif
-rw-r--r-- 1 root root 0 Oct 26 12:47 ylt.gif
[root@web001 scripts]# cat 222.sh
#!/bin/bash
cd test
for filename in `ls|grep "gif$"`
do
mv $filename `echo $filename|cut -d . -f1`.txt
done
[root@web001 scripts]# sh 222.sh
[root@web001 scripts]# ll test/
total 0
-rw-r--r-- 1 root root 0 Oct 26 12:47 test.txt
-rw-r--r-- 1 root root 0 Oct 26 12:47 ylt.txt
法 2:通过 rename 命令实现
[root@web001 test]# rename "txt" "gif" *.txt
[root@web001 test]# ll
total 0
-rw-r--r-- 1 root root 0 Oct 26 12:47 test.gif
-rw-r--r-- 1 root root 0 Oct 26 12:47 ylt.gif
例 10-4
在 Linux 下批量修改文件名,将 “_finished” 去掉。
[root@web001 test]# ll
total 4
-rw-r--r-- 1 root root 95 Oct 26 14:48 223.sh
-rw-r--r-- 1 root root 0 Oct 26 14:44 test_1_finished.jpg
-rw-r--r-- 1 root root 0 Oct 26 14:44 test_2_finished.jpg
[root@web001 test]# cat 223.sh
#!/bin/bash
for file in `ls *.jpg`
do
mv $file `echo $file|sed 's/_finished//g'`
#mv $file `