Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check to see if a file exists on a remote server using shell

Tags:

shell

I have done a lot of searching and I can't seem to find out how to do this using a shell script. Basically, I am copying files down from remote servers and I want to do something else if it doesn't exist. I have an array below, but I tried to reference it directly, but it is still returning false.

I am brand new at this, so please be kind :)

declare -a array1=('[email protected]');

for i in "${array1[@]}"
do
   if [ -f "$i:/home/user/directory/file" ];
   then
     do stuff
   else
     Do other stuff
   fi
done
like image 752
Brandy Avatar asked Apr 24 '15 19:04

Brandy


People also ask

How do I check if a file exists 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 is present in a directory in Linux?

The -e flag is to check whether the files or the directories exist or not. The -f flag is to check whether the ordinary files (not directories) exist or not. Finally, the -d flag is to check whether this is a directory or not. This flag cannot accept the wildcard argument.


1 Answers

Try this:

ssh -q $HOST [[ -f $i:/home/user/directory/file ]] && echo "File exists" || echo "File does not exist";

or like this:

if ssh $HOST stat $FILE_PATH \> /dev/null 2\>\&1
then
  echo "File exists"
else
  echo "File not exist"
fi
like image 124
Rahul Tripathi Avatar answered Oct 29 '22 18:10

Rahul Tripathi