0

I have a list of files that must exist in a remote directory before I send out a confirmation email. For example, my list is: file_list=example.txt testfile.txt. I know how to test if each individual file exists as such:

ssh here@ip.addr "test -e /path/to/file/example.txt"
if [ $? -eq 0 ]; then
    echo -e "Email body" | mail -s "File exists." "some.email@email.com"
fi

But how can I hit each file in the list and confirm that all files exist in this remote directory? Say three out of four were successfully pushed via sftp, I'd need to exit with an e-mail error to my group only saying go check it out rather than proceeding to email the client that all files are available. The logic is perhaps something like:

ssh here@ip.addr "test - [$file_list]"
if [they all exist]; then
  successful -- email the client
else
  error -- email your group
  exit
fi
2

You could try to set up an array on the remote side of a single ssh connection and loop through it; if the list of files is static and you can drop a shell script on the remote side, calling it may be easiest. Otherwise, you could set the array up locally and loop over it, ssh'ing in each time to test for the file's existence:

files=(example.txt testfile.txt)
ok=0
for file in "${files[@]}"
do
  ssh here@ip.addr test -e "$file" && ((ok++))
done
if [ $ok -eq ${#files[@]} ]
then
  success, all $ok files made it
else
  failure, only $ok files made it
fi
  • I'm getting a binary operator error after the ssh step but this is essentially what I want -- thanks! The error is test: /remote/path/example.txt: binary operator expected. – kstats9pt3 Sep 13 '17 at 18:57
  • ssh here@ip.addr test -e "$file" && ((ok++)) should be ssh here@ip.addr 'test -e "$file" && ((ok++))' Forgot quotes :P – Hunter.S.Thompson Sep 13 '17 at 19:01
  • Single-quoting the entire thing will prevent expansion of $file – Jeff Schaller Sep 13 '17 at 19:18
  • Single quoting actually does not work for me -- the ANSWER ABOVE works: ssh here@ip.addr test -e "$dir/$date/$file" && ((ok++)). My array would not take my file_list i.e. files=($file_list) so I had to explicitly define that array. – kstats9pt3 Sep 13 '17 at 19:28
0

Set the variable file and file1 and add the names of the files.

file="/path/to/testfile.txt"
file1="/path/to/example.txt"

ssh here@ip.addr
if [[ -f "$file" && -f "$file1" ]]; then
    echo -e "Email body" | mail -s "File exists." "some.email@email.com"
else
  echo -e "Email body" | mail -s "File does not exists." "some.email@email.com"
  exit
fi

-f : Return true value if file exists and is a regular file.

  • This is a little too much hard coding. The file names and numbers change daily, so -f file1, -f file2, etc. is going to vary greatly. – kstats9pt3 Sep 13 '17 at 18:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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