要求:写一个linux bash脚本来查看目标文件夹下所有的file和directory,并且打印出他们的绝对路径。
运行command:./myDir.sh input_path output_result
要求输出格式为:
代码思路:
BFS遍历,数据结构为queue,数组实现。
代码实现:
#!/bin/bash SAVEIFS=$IFS IFS=$(echo -en "\n\b") #处理特殊字符文件名 queue[0]="head" path_[0]='' head_index=0 #head = the first inde - 1 tail_index=1 #tail=length the last index + 1
head="null" dir_count=0 file_count=0 path=`` #if the output directory is not exist, make a new directory #处理目标文件所处地址不存在问题 out_path=$2 e_path=""
while [ ${out_path##*/} != ${out_path%%/*} ] do dir_name=${out_path%%/*} if [ ! -e $e_path""$dir_name ] then mkdir $e_path""$dir_name fi e_path=$e_path""$dir_name"/" out_path=${out_path#*/} done
touch $2 #use queue to take BFS function enQueue(){ #insert into tail queue[${tail_index}]=$1 path_[${tail_index}]=$path"/"$1 tail_index=$((${tail_index}+1)) } function deQueue(){ #dequeue from head head_index=$((${head_index}+1)) head=${queue[head_index]} } #start of this program enQueue $1
while [ ${head_index} -ne $((${tail_index}-1)) ] do deQueue path_[1]=`pwd`"/"$1 path=${path_[$head_index]} echo "["${head}"]" >>$2
for var in `ls ${path_[$head_index]}` do
if [ -d $path"/""${var}" ] then dir_count=$((${dir_count}+1)) enQueue $var fi
echo $path"/""${var}" >>$2 file_count=$((${file_count}+1)) done
echo "" >>$2
done file_count=$((${file_count}-${dir_count})) echo "[Directories Count]:"${dir_count} >>$2
echo "[Files Count]:"$file_count >>$2 IFS=$SAVEIFS
写作业的时候遇到了很多小问题,因为自己也是刚刚才接触到shell,总结了一些解决方法,放在了另一篇随笔里。