Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test for if two files exist?

Tags:

linux

bash

I would like to check if both files exist, but I am getting

test.sh: line 3: [: missing `]' 

Can anyone see what's wrong?

#!/bin/sh  if [ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]; then    echo "both exist" else    echo "one or more is missing" fi 
like image 222
Sandra Schlichting Avatar asked Jan 23 '12 11:01

Sandra Schlichting


People also ask

How do you validate if two files are the same or not?

Probably the easiest way to compare two files is to use the diff command. The output will show you the differences between the two files. The < and > signs indicate whether the extra lines are in the first (<) or second (>) file provided as arguments.

How do you check if files exist in Linux?

When checking if a file exists, the most commonly used FILE operators are -e and -f . The first one will check whether a file exists regardless of the type, while the second one will return true only if the FILE is a regular file (not a directory or a device).

How do you check if a file exists or not empty?

You can use the find command and other options as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data.

How do I find the common string in two files?

Use comm -12 file1 file2 to get common lines in both files. You may also needs your file to be sorted to comm to work as expected. Or using grep command you need to add -x option to match the whole line as a matching pattern. The F option is telling grep that match pattern as a string not a regex match.


2 Answers

Try adding an additional square bracket.

if [[ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]]; then 
like image 52
Raghuram Avatar answered Sep 29 '22 01:09

Raghuram


[ -f .ssh/id_rsa -a -f .ssh/id_rsa.pub ] && echo both || echo not 

or

[[ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]] && echo both || echo not 

also, if you for the [[ ]] solution, you'll probably want to change #!/bin/sh to #!/bin/bash in compliance with your question's tag.

like image 36
Michael Krelin - hacker Avatar answered Sep 29 '22 00:09

Michael Krelin - hacker