0

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.

2
  • 5
    Please edit your question and explain what do you want to achieve with the wrong echo command. Do you mean something like [ -e ./documents_2019-12-12.tar.gz ] && echo "file exists"? You can combine multiple checks, e.g. [ -e file1 ] && [ -e file2 ] && [ -e file3 ] && echo "all files exist"
    – Bodo
    Commented Dec 16, 2019 at 10:44
  • Also, you can test the existence on possibly multiple files use the following one liner: for i in /my/path/files.*; do test -f "$i" && echo "exists one or more files" && break; done. See this thread for explanations
    – Maxime B.
    Commented Dec 16, 2019 at 10:45

1 Answer 1

2

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.