bash/perl判断文件是否存在,以及常见应用场景

29 篇文章 11 订阅

一、 源代码实现

个人常见场景,大多出现在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. 根据文本内容判断时,也要先检查这个文本是否已存在,避免不必要的脚本执行问题。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值