欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

shell檢測某個文件/文件夾是否存在詳細實例

 更新時間:2023年06月27日 08:42:49   作者:frostjsy  
shell是一個用?C?語言編寫的程序,它是用戶使用Linux的橋梁,下面這篇文章主要給大家介紹了關于shell檢測某個文件/文件夾是否存在的相關資料,需要的朋友可以參考下

1、shell檢測某一文件是否存在

當你在shell中需要檢查一個文件是否存在時,通常需要使用到文件操作符-e和-f。第一個-e用來檢查文件是否存在,而不管文件類型。第二個-f僅僅用來檢查文件是常規(guī)文件(不是目錄或設備)時返回true。

FILE=/etc/resolv.conf
if test -f "$FILE"; then
    echo "$FILE exist"
fi
FILE=/etc/resolv.conf
if [ -f "$FILE" ]; then
    echo "$FILE exist"
fi
FILE=/etc/resolv.conf
if [[ -f "$FILE" ]]; then
    echo "$FILE exist"
fi

2、shell檢測某一目錄是否存在

Linux系統(tǒng)中運算符-d允許你測試一個文件是否時目錄。

例如檢查/etc/docker目錄是否存在,你可以使用如下腳本:

FILE=/etc/docker
if [ -d "$FILE" ]; then
    echo "$FILE is a directory"
fi
[ -d /etc/docker ] && echo "$FILE is a directory"

3、檢查文件是否不存在

和其他語言相似,test表達式允許使用!(感嘆號)做邏輯not運算,示例如下:

FILE=/etc/docker
if [ ! -f "$FILE" ]; then
    echo "$FILE does not exist"
fi
[ ! -f /etc/docker ] && echo "$FILE does not exist"

4、檢查是否存在多個文件

不使用復雜的嵌套if/else構造,您可以使用-a(或帶[[的&&預算符)來測試是否存在多個文件,示例如下:

if [ -f /etc/resolv.conf -a -f /etc/hosts ]; then
    echo "Both files exist."
fi
if [[ -f /etc/resolv.conf && -f /etc/hosts ]]; then
    echo "Both files exist."
fi

5、應用實例

只跑一遍diff的時候,可能因為環(huán)境不穩(wěn)定導致diff,因此循環(huán)跑某個場景的diff query。具體實現(xiàn)如下,get_diff.py結合具體的場景定,-input_file ${result_dir}/${query_file}_${head}   -output_file ${result_dir}/${query_file}_${behind}這兩個文件一樣。

base="501"
exp="506"
iter_num=2
query_name="model_iter_v2"
data_dir=./data_${query_name}
result_dir=./result_${query_name}
if [ ! -d "${result_dir}" ]; then
    mkdir ${result_dir}
fi
if [  -d "${result_dir}" ]; then
    rm -rf ${result_dir}/*
fi
for var in  ${data_dir}/*; do
    query_file=${var##*/}
    cp ${data_dir}/${query_file} ${result_dir}/${query_file}_1
    head=1
    while [[ ${head} -lt ${iter_num} ]]
    do
        behind=$((${head} + 1))
        echo ${query_file}_${head}
        echo ${query_file}_${behind}
        python get_diff.py -input_file ${result_dir}/${query_file}_${head}  -b ${base} -e ${exp}  -output_file ${result_dir}/${query_file}_${behind} > ${query_file}.log
        sort -t"    " -k2,2nr ${result_dir}/${query_file}_${behind}_result > ${result_dir}/${query_file}_${behind}
        rm ${result_dir}/${query_file}_${behind}_result
        if [ ${behind} -eq ${iter_num} ]; then
            cp ${result_dir}/${query_file}_${behind} ./${query_file}_diff
        fi
        let head++
    done
done

參考:Linux中Shell腳本判斷文件或文件夾是否存方法

總結

到此這篇關于shell檢測某個文件/文件夾是否存在的文章就介紹到這了,更多相關shell檢測文件夾是否存在內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論