0

Wondering what is wrong with my syntax.

Running this bash script works as expected and all of the commands are executed:

sftp -i ~/.ssh/my_private_key $username@$host <<EOF
lcd /home/documents
get *
bye
EOF

Trying to throw the EOF inside of an IF, however, makes it not execute:

sftp -i ~/.ssh/my_private_key $username@$host

if [[ $? != 0 ]]; then
    echo "SFTP connection failed to establish."
    exit 10
else <<-EOF
    lcd /home/documents
    get *
    bye
    EOF
    echo "Files moved and connection closed."
fi

exit 0

All that happens is I see the "Connected to $host" message in terminal, and then it waits for input. If I type any commands like ls or pwd they execute, and finally typing bye closes the connection and prints "Connection closed.", but none of the commands inside EOF execute at any point.

3
  • if [[ $? != 0 ]]; then should be if [[ $? -ne 0 ]]; then Feb 27 '20 at 22:32
  • @guillermochamorro The script behaves exactly the same with that change. Feb 27 '20 at 22:38
  • I was just pointing out that for arithmetic comparisons you have to use -ne,-eq,-lt etc, for string comparisons you use =,!=. Feb 27 '20 at 22:41
4

The redirection should be applied to the sftp command, so the if should look something like:

if sftp -i ~/.ssh/my_private_key $username@$host  <<-EOF
lcd /home/documents
get *
bye
EOF
then
    echo "Files moved and connection closed."
else
    echo "SFTP connection failed to establish."
    exit 10
fi

After all, if the connection failed to get established, it doesn't matter if the commands are sent or not, so send them anyway.

3
  • Also, the test on $? tests the exit status of sftp, which is only defined after sftp exits. After it’s exited, it’s too late to send it input. Feb 28 '20 at 6:35
  • Can the status of sftp be tested without exiting it? Feb 28 '20 at 18:02
  • By definition, the exit status is returned after exiting.
    – muru
    Feb 29 '20 at 0:58

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.