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 Commented Feb 27, 2020 at 22:32
  • @guillermochamorro The script behaves exactly the same with that change. Commented Feb 27, 2020 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 =,!=. Commented Feb 27, 2020 at 22:41

1 Answer 1

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. Commented Feb 28, 2020 at 6:35
  • Can the status of sftp be tested without exiting it? Commented Feb 28, 2020 at 18:02
  • By definition, the exit status is returned after exiting. Commented Feb 29, 2020 at 0:58

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.