bash/perl判斷文件是否存在,以及常見應用場景

一、 源代碼實現

個人常見場景,大多出現在linux shell或者perl裏。

#!/bin/bash
file="/etc/hosts"
if [ -f "$file" ]
then
 echo "$file found."
else
 echo "$file not found."
fi
#!/usr/bin/perl -w  

my $file = "/etc/hosts";  
if(-e $file){  
    print "$file exist. \n";  
}else{  
    print "$file not found. \n";  
}  

解釋:
-e pathname
True if pathname resolves to a file that exists. False if pathname cannot be resolved.
-f pathname
True if pathname resolves to a file that exists and is a regular file. False if pathname cannot be resolved, or if pathname resolves to a file that exists but is not a regular file.

regular file的意義是,常規文件,用ls -l命令查看,(例如-rw-r—–)的第一個字母來區分;
-就代表普通文件,
d代表目錄文件,
l代表軟連接文件等.

二、 常見應用場景

  1. 跑流程時,判斷上一步驟是否完成;可以讓上一步驟的程序,執行到某流程結束時,產生一個文件。比如fpga綜合工具synplify,因爲當前license非float,不支持exit命令,只能使用圖形界面;之前使用sleep 5h方式,會浪費很多等待時間,而且等待時間並不可靠;現在可以使用判斷文件是否存在的方式,得到可靠的等待時間。
  2. 根據文本內容判斷時,也要先檢查這個文本是否已存在,避免不必要的腳本執行問題。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章