How to create directory if doesn’t exists in sftp

sftpshell

I want to create a directory if it doesn't exists after login to sftp server.

test.sh

sftp name@example.com << EOF
mkdir test
put test.xml
bye
EOF

Now i call test.sh and upload different files each time to test folder. When running this

mkdir test

First time it works and second time it throws Couldn't create directory: Failure error?

How to create a directory if doesn't exists and if exists don't create directory in sftp.

Best Solution

man 1 sftp (from openssh-client package):

-b batchfile

    Batch mode reads a series of commands from an input
    batchfile instead of stdin. Since it lacks user
    interaction it should be used in conjunction with
    non-interactive authentication. A batchfile of ‘-’
    may be used to indicate standard input. sftp will
    abort if any of the following commands fail: get,
    put, reget, reput, rename, ln, rm, mkdir, chdir, ls,
    lchdir, chmod, chown, chgrp, lpwd, df, symlink, and
    lmkdir. Termination on error can be suppressed on a
    command by command basis by prefixing the command
    with a ‘-’ character (for example, -rm /tmp/blah*).

So:

{
  echo -mkdir dir1
  echo -mkdir dir1/dir2
  echo -mkdir dir1/dir2/dir3
} | sftp -b - $user@$host