Home » Linux » How to test for if two files exist?

How to test for if two files exist?

Posted by: admin November 30, 2017 Leave a comment

Questions:

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
Answers:

Try adding an additional square bracket.

if [[ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]]; then

Questions:
Answers:
[ -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.

Questions:
Answers:

[[ is bash-specific syntax. For POSIX-compatible shells, you need:

[ -f file1 ] && [ -f file2 ]

Questions:
Answers:
if [ -e .ssh/id_rsa -a -e .ssh/id_rsa.pub ]; then
 echo "both exist"
else
 echo "one or more is missing"
fi

Here,

-e check only the file is exits or not.If exits,it return true.else,it return false.

-f also do the same thing but,it check whether the given file is regular file or not.based on that it return the true/false.

Then you are using &&.So that,It need two [[ .. ]] brackets to execute.

instead you can use the -a [same as && operator] -o [same as || operator].
If you need more information go through this link

http://linux.die.net/man/1/bash.