bashshellsftp

Passing variables to sftp batch


I'm writing a script that needs to pass a variable to the sftp batch. I have been able to get some commands working based on other documentation I've searched out, but can't quite get to what I need.

The end-goal is to work similar to a file test operator on a remote server: ( if [ -f "$a" ] then :; else exit 0;)

Ultimately, I want the file to continue running the script if the file exists (:), or exit 0 if it does NOT exist (not exit 1). The remote machine is a Windows server, not Linux.

Here's what I have:

NOTE - the variable I'm trying to pass, $source_dir, changes based on the input parameter of the script that calls this function. This and the ls wildcard is the tricky part. I have been able to make it work when looking for a specific file, but not just "any" file.

source_dir=/this/directory/changes

RemoteCheck () {

    /bin/echo "cd $source_dir" > someBatch.txt
    /bin/echo "ls *" >> someBatch.txt

    /usr/bin/sftp -b someBatch.txt -oPort=${sftp_port} ${sftp_ip}

    exit_code=$?;
    if [ $exit_code -eq 0 ]; then
        :
    else
        exit 0
    fi
}

There may be a better way to do this, but I have searched multiple forums and have not yet found a way to manipulate this.


Solution

  • You cannot test for existence of any file using just exit code of the OpenSSH sftp.

    You can redirect the sftp output to a file and parse it to see if there are any files.

    You can use shell echo command to delimit the listing from the rest of the output like:

    !echo listing-start
    ls
    !echo listing-end