Shell练习:遍历文件夹下的所有文件及文件夹,并输出到文件

 


脚本练习

1.切换工作目录至/var        

2.依次向/var目录中的每个文件或子目录问好,形如:(提示:for FILE in /var/*;或for FILE in `ls /var`;)       

3.统计/var目录下共有多个文件,并显示出来   


Discription: 遍历指定文件夹下的所有文件,并输出到文件。

Example 1:

#!/bin/bash -


Total_dir=0


# Function for detect the dir
Hi_Dir () {
    #echo ".....llllll$1"
    #echo "....$Total_dir, Input is $1"
    FILE=$1
    if test -d $FILE
    then
        num=`ls $FILE | wc -l `
    else
        num=0
    fi
    #echo "There are $num file under $1"
    if test -d $FILE -a $num -gt 0
    then
        #echo "Enter into new dir $FILE"
    for FILE1 in $FILE/* 
    do
        #echo "We are here"
    Hi_Dir $FILE1
    done
    else
    echo "Hi `basename $FILE`, your address is  `dirname $FILE`!!!"
    Total_dir=$[Total_dir +1]
    fi
    
    
    #for FILE in `$1`
    #do
    #echo "llllll"
    #if test -d $FILE
    #then
    # Hi_Dir $FILE/*
    #fi
    #echo "Hi $FILE, your name is $(basename $FILE)!!!"
    #done
    
}
for lll in /var/*
do
Hi_Dir $lll
done


echo "Thare are total $Total_dir files!!!"



Example 2:

#!/bin/bash -




##################################################
# This scripts is uesed to run PrimeTime,
# You could get help by type "run_pt.bash -h"
#################################################




# Function: Usage
Usage () {
echo "***********************************************" >&2
    echo "[Info]       Example:$0 dir_path  [-o file_list.txt]  "
echo "***********************************************" >&2
    exit 1
}




# Function for detect the dir
Hi_Dir () {
    FILE=$1
    if test -d $FILE
    then
        num=`ls $FILE | wc -l `
    else
        num=0
    fi
    #echo "There are $num file under $1"
    if test -d $FILE -a $num -gt 0
    then
        #echo "Enter into new dir $FILE"
    for FILE1 in $FILE/* 
    do
        #echo "We are here"
    Hi_Dir $FILE1
    done
    else
    #echo "Hi `basename $FILE`, your address is  `dirname $FILE`!!!"
    echo $FILE >> $2
    Total_dir=$[Total_dir +1]
    fi
}


# Main Parameter
Total_dir=0
out_file=file_list.txt


if [[ $# = 0 ]]; then
Usage
fi


# Main Function
echo "[Info] your option is $* "
dir_path=$1
shift


while [ $# -gt 0 ]
do
case $1 in
-o) out_file=$2
shift 2
;;
-h | -help) Usage
;;
--) shift
#break
;;
-*) echo $0:$1 : unrecognised option >&2
shift
;;
esac
done


if test -d $dir_path 
then
echo "[Info] Begin to recuision dir : $dir_path" 
else
echo "[Error] Please input the correct dir path! $dir_path"
Usage
fi


if test -d $out_file 
then
echo "File exists"
else
echo "Make new file"
touch $out_file
fi




for lll in $dir_path
do
Hi_Dir $lll $out_file
done


echo "Thare are total $Total_dir files!!!"


你可能感兴趣的:(Shell)