2

I am trying to write a Bash script responsible for creating a folder on a remote server.

Snippet:

!/bin/bash -e
echo "Creating remote folder."
echo mkdir test_folder | sftp -oPort=22 192.168.0.11:/tmp
if [[ $? != 0 ]]; then
  echo "Transfer failed!"
  exit 1
else
  echo "Transfer complete."
fi
echo $?

The output is:

Connected to 192.168.0.11.
Changing to: /tmp
sftp> mkdir test_folder
Couldn't create directory: Failure
Transfer complete.
0

So there return code is 0 but obviously there was an error.

How can I catch the remote error and set an appropriate return code in the script?

1
6

Use sftp's option -b (with a batchfile or bash's Process Substitution) and you'll get mkdir's return code.

sftp -b <(echo "mkdir test_folder") user@remotehost:/
echo $?

Output:

Changing to: /
sftp> mkdir test_folder
Couldn't create directory: Failure
1

or use this:

echo "mkdir test_folder" | sftp -b - user@remotehost:/
echo ${PIPESTATUS[1]}

From man sftp:

-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, 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*).

1
  • Thanks! Preferred the second option as it seems POSIX compliant. – Valentin Despa Aug 17 '15 at 9:10
0

1) The usage of the $? variable is not correct. The problem is that you need to store the return value ($?) immediately after executing the sftp command. Otherwise you will get return value of another command. E.g.:

rm /directory_which/does_not_exists
echo $?
echo "Deleting directory ..."

is totaly different than:

rm /directory_which/does_not_exists
echo "Deleting directory ..."
echo $?

2) You can create remote directory by using ssh as well like

ssh username@192.168.0.11 "cd /tmp && mkdir test_folder"

Hope it helps...

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.