简体   繁体   English

Bash中存在测试文件

[英]Test file existence in Bash

I want to test existence of a file using a Bash script of but get "no file exists..." message even if the file ACTUALLY exists: 我想使用Bash脚本测试文件的存在,但是即使文件实际存在,也会收到“ no file exist ...”消息:

#!/bin/bash
# Usage : myscript.sh AAAAMMJJ
# where AAAAMMJJ is the argument passed to the script  

d_date=$1

# No accurate content here...
# $d_date value is 20160708
# $d_year value is 2016
# $d_month value is 07
# $d_day value is 08

# Directory path
p_path="/home/user/mydir/${year}"

# Filename is something like: my-file_20160708z.html
f_file="${$p_path}/my-file_${d_date}z.html"

# Testing if file exists
[ ! -f "${f_file}" ] && echo "File OK" || echo "no file..."

What is the proper way to test file existence with this kind of construct? 用这种结构测试文件存在的正确方法是什么? This works perfectly with another file (".txt" file). 这与另一个文件(“ .txt”文件)完美配合。

You wrote: 你写了:

# Testing if file exists
[ ! -f "${f_file}" ] && echo "File OK" || echo "no file..."

What you should have written: 您应该写的内容:

# Testing if file exists
[ -f "${f_file}" ] && echo "File OK" || echo "no file..."

Explanation 说明

man test : man test

( EXPRESSION ) (表示)

EXPRESSION is true 表达是真的

! EXPRESSION 表达

EXPRESSION is false 表达式为假

So when you write just an expression, success means true. 因此,当您仅编写表达式时,成功就意味着成功。

-f FILE -f文件

FILE exists and is a regular file FILE存在并且是常规文件

So, if you wanted to test a file exists, you wouldn't negate the -f test by putting a ! 因此,如果您要测试文件是否存在,则不要通过输入!否定-f测试! , that would do the opposite. ,那将相反。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM