[operating system job lab1] linux shell script traverses the target folder and all files, including the processing of special character file names

Requirement: write a linux bash script to view all file s and directories in the target folder, and print out their absolute path.

Run command:. / myDir.sh "input" path "output" result

The required output format is:

 

 

Code idea:

BFS traversal, data structure is queue, array implementation.

Code implementation:

#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")  #Process special character file names


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
#There is no problem processing the address of the target file

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

 

I encountered many small problems when I was writing my homework, because I just touched the shell, summed up some solutions, and put them in another article Informal essay Li.

 



Tags: Linux shell

Posted on Wed, 04 Dec 2019 03:54:09 -0500 by itsmeArry