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"

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
  error -- email your group

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)
for file in "${files[@]}"
  ssh here@ip.addr test -e "$file" && ((ok++))
if [ $ok -eq ${#files[@]} ]
  success, all $ok files made it
  failure, only $ok files made it
  • 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

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


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

-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.