天天看點

判斷指定目錄是否有檔案

linux 中如何判斷指定目錄下是否有檔案(包括隐藏檔案和符号連結)呢?

腳本名:decide_blank_folder.sh

腳本内容:

判斷指定目錄是否有檔案

#!/bin/sh  

# whether the specified folder has files,including symbolic file and hidden file  

is_blank_dir_yes=2  

is_blank_dir_no=5  

ishasfileindir()  

{  

        result3=`find "$1" ! -type d`  

        if [ x"$result3" == x"" ];then  

                return 1  

                # has no file  

        else  

        echo "$this_dir"  

                return 3  

                # has file(s)  

        fi  

}  

is_blank_folder_compl()  

        local fold_name="$1"  

        ls "$fold_name" >/dev/null 2>&1  

        if [ $? -ne 0 ];then  

                return 4  

                # has no this folder  

        local result=`ls -a "$fold_name"`  

        if [ x"$result" == x"" ];then  

                return $is_blank_dir_yes  

                # is blank  

         else  

                for i in `find "$fold_name" ! -type d`;do  

                        return $is_blank_dir_no  

                done  

                #init_bool=5  

         fi  

if [ -z "$1"  ];then  

    echo "no argument";  

        exit 255  

fi  

is_blank_folder_compl "$1"  

retval=$?  

echo "return value: $retval"  

if [ $retval -eq $is_blank_dir_yes ];then  

        echo "has no file(s)"  

else  

        if [ $retval -eq $is_blank_dir_no ];then  

                echo "has file......."  

測試如下:

[root@localhost test]# ./decide_blank_folder.sh abc/

return value: 2

has no file(s)

知識點補充:

(1)如何檢視隐藏檔案?

使用ls -a

(2)`find "$fold_name" ! -type d` 中的感歎号表示什麼?

表示否定,即搜尋除檔案夾之外的所有内容,搜尋時排出檔案夾。

繼續閱讀