Lecagy
Lecagy

Reputation: 489

Test if a file exists

I struggle with the examples given if a file exists. I want to check if multiple files exists in order to perform further operations.

ls -al:  
    -rwxrwxrwx 1 root   tomcat         6 Dec 16 11:25 documents_2019-12-12.tar.gz  

echo < [ -e ./documents_2019-12-12.tar.gz ]:  
    bash: [: No such file or directory  

Can somebody tell me what i'm doing wrong?

Edit: I have a backup direcory with two files:

database_date.sql
documents_date.tar.gz

I need to check if both files for a given date are available. The directory shall contain these file-pairs for several dates.

Upvotes: 0

Views: 1401

Answers (1)

Aisling Brown
Aisling Brown

Reputation: 36

What you have here is a misunderstanding of where specific syntax is used. The [ -e ./documents_2019-12-12.tar.gz ] part of your command is syntax specific to the if clause in bash. Here's an example

if [ -e ./documents_2019-12-12.tar.gz ]
    then 
        echo "File Exists!"
fi

The square brackets [] are used to surround the check being performed by the if statement and the -e flag is specific to these if checks. More info here http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

To explain the error you're seeing, the < operator takes a file to the right and feeds the contents to the command on the left. In your case the < sees the [ as the thing on the right so we try and read it as a file. Such a file doesn't exist so bash helpfully tells you that there's an error (the bash: [: No such file or directory bit) and then quits out.

Upvotes: 2

Related Questions