【操作系统作业—lab1】linux shell脚本 遍历目标文件夹和所有文件 | 包括特殊字符文件名的处理

时间:2023-03-09 05:42:24
【操作系统作业—lab1】linux shell脚本 遍历目标文件夹和所有文件 | 包括特殊字符文件名的处理

要求:写一个linux bash脚本来查看目标文件夹下所有的file和directory,并且打印出他们的绝对路径。

运行command:./myDir.sh  input_path  output_result

要求输出格式为:

【操作系统作业—lab1】linux shell脚本 遍历目标文件夹和所有文件 | 包括特殊字符文件名的处理

代码思路:

BFS遍历,数据结构为queue,数组实现。

代码实现:

#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b") #处理特殊字符文件名 queue[]="head"
path_[]=''
head_index= #head = the first inde -
tail_index= #tail=length the last index +
head="null"
dir_count=
file_count=
path=`` #if the output directory is not exist, make a new directory
#处理目标文件所处地址不存在问题 out_path=$
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 $ #use queue to take BFS function enQueue(){ #insert into tail
queue[${tail_index}]=$
path_[${tail_index}]=$path"/"$
tail_index=$((${tail_index}+))
} function deQueue(){ #dequeue from head
head_index=$((${head_index}+))
head=${queue[head_index]}
} #start of this program
enQueue $
while [ ${head_index} -ne $((${tail_index}-)) ]
do
deQueue
path_[]=`pwd`"/"$
path=${path_[$head_index]}
echo "["${head}"]" >>$ for var in `ls ${path_[$head_index]}`
do
if [ -d $path"/""${var}" ] then
dir_count=$((${dir_count}+))
enQueue $var
fi
echo $path"/""${var}" >>$
file_count=$((${file_count}+))
done
echo "" >>$
done file_count=$((${file_count}-${dir_count}))
echo "[Directories Count]:"${dir_count} >>$
echo "[Files Count]:"$file_count >>$ IFS=$SAVEIFS

写作业的时候遇到了很多小问题,因为自己也是刚刚才接触到shell,总结了一些解决方法,放在了另一篇随笔里。