问题如下:
我想要在脚本中传递一个参数(参数是想遍历的目录),然后递归地列出目录下的文件夹,把文件夹排序之后从1开始编号。
PS:这个问题起源是我想听歌,但是用mplayer只能直接用文件作参数,不能传递目录(或许可以但我不知道),于是想做一个传递目录的脚本。
下面是歌曲目录:
drwxr-xr-x 2 darkfish darkfish 4096 2009-08-01 20:47 High school musical 1
drwxr-xr-x 2 darkfish darkfish 4096 2009-08-01 20:47 High school musical 2
drwxr-xr-x 2 darkfish darkfish 4096 2009-08-01 20:47 High school musical 3
drwxr-xr-x 2 darkfish darkfish 4096 2009-09-04 12:05 linkin park
drwxr-xr-x 2 darkfish darkfish 4096 2009-09-25 08:42 Music
drwxr-xr-x 4 darkfish darkfish 4096 2009-08-01 20:47 未知艺术家1
drwxr-xr-x 4 darkfish darkfish 4096 2009-08-01 20:47 未知艺术家2
drwxr-xr-x 2 darkfish darkfish 4096 2009-08-01 20:47 歌词
假设脚本名字叫做 music.sh,调用形式为:
$music.sh ~/Music
如果用
for file in $(ls)
do
echo "$file"
echo -------
done
这里会输出:
High
school
musical
High
school
musical
2
High
school
musical
3
linkin
park
Music
未知艺术家1
未知艺术家2
歌词
完全不是我们想要的。
这里涉及到了断行的符号。
在for循环里面,默认的是空格。而断行的符号在 shell中是保存在IFS变量中:
于是产生了下列办法:
#!/bin/bash
direc="/home/darkfish/Music/Entertainment/"
OLDIFS=$IFS //备份很重要
IFS=:
count=0
for file in $( find $direc -type d -printf "%p$IFS")
do
let "count += 1"
echo "[#$count] $file"
echo ---------
done
echo ==============
IFS=$OLDIFS //再把IFS挪回来。
测试的结果是:
[darkfish 23:12 #18]:~/programming/bash/formusic$ ./test.sh
[#1] /home/darkfish/Music/Entertainment/
---------
[#2] /home/darkfish/Music/Entertainment/High school musical 3
---------
[#3] /home/darkfish/Music/Entertainment/Music
---------
[#4] /home/darkfish/Music/Entertainment/歌词
---------
[#5] /home/darkfish/Music/Entertainment/High school musical 2
---------
[#6] /home/darkfish/Music/Entertainment/未知艺术家1
---------
[#7] /home/darkfish/Music/Entertainment/未知艺术家1/未知唱片集 (2009-7-24 12-28-19)
---------
[#8] /home/darkfish/Music/Entertainment/未知艺术家1/未知唱片集 (2009-7-24 12-28-20)
---------
[#9] /home/darkfish/Music/Entertainment/未知艺术家2
---------
[#10] /home/darkfish/Music/Entertainment/未知艺术家2/未知唱片集 (2009-7-24 12-38-07)
---------
[#11] /home/darkfish/Music/Entertainment/未知艺术家2/未知唱片集 (2009-7-24 12-38-08)
---------
[#12] /home/darkfish/Music/Entertainment/High school musical 1
---------
[#13] /home/darkfish/Music/Entertainment/linkin park
---------
BINGO,完美解决…………
但肯定还有其他的办法,等想到之后再补充。
论坛牛人提出新方法了:
while IFS= read -r -d $'\0' file; do a[i++]="$file" done < <(find /tmp -type f -print0)
膜拜Orz
阅读(726) | 评论(0) | 转发(0) |