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
總結
到此這篇關于shell檢測某個文件/文件夾是否存在的文章就介紹到這了,更多相關shell檢測文件夾是否存在內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
awk實現(xiàn)Left、join查詢、去除重復值以及局部變量講解例子
這篇文章主要介紹了awk實現(xiàn)Left、join查詢、去除重復值以及局部變量講解例子,awk的高級使用技巧,需要的朋友可以參考下2014-07-07linux上搭建solr的實現(xiàn)方法(用jetty部署)
下面小編就為大家分享一篇linux上搭建solr的實現(xiàn)方法(用jetty部署),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12shell命令while循環(huán)中使用sleep命令代碼示例
這篇文章主要介紹了shell命令while循環(huán)中使用sleep命令代碼示例,分享了相關代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02