如何在SFTP执行结束时执行shell脚本?

3

我有一个shell脚本,在其中我执行SFTP并将文件传输到远程主机。

我可以将文件传输到远程主机,但是一旦完成SFTP,我的父shell脚本代码就无法执行。

#!/bin/bash
set -e
echo "Starting SFTP..."
    cd "/Users/myuser/myfolder"
    sftp -o "StrictHostKeyChecking no" admin@myserver.myorg.com << END_SCRIPT
    cd /some/folder/on/remote/host
    put -r .
    bye
    END_SCRIPT
echo "Done."

我看不到控制台上打印出“Done.”的信息。有什么线索吗?

1
你的脚本真的像问题中显示的那样缩进吗? - Leon
是的,没错。我对这个还很陌生。我应该不缩进吗? - Akshay Lokur
2
取消缩进(或仅取消END_SCRIPT行的缩进)肯定会解决问题。 - Leon
很棒,问题解决了 :) 谢谢。但是,这是什么原因呢? - Akshay Lokur
或者,如果缩进是通过制表符进行的,您可以使用<<- END_SCRIPT语法(注意破折号符号)。 - Leon
好的,你能把这个作为答案发出来并附上理由吗?我会标记为已接受,谢谢。 - Akshay Lokur
2个回答

4

这个问题是由于缩进引起的。有两种可能的解决方法:

  1. 要么消除缩进(至少对于END_SCRIPT行),
  2. 要么确保缩进是使用制表符而不是空格,并使用<<-重定向运算符而不是<<

您还必须确保在END_SCRIPT之后没有空白。

Here Documents

This type of redirection instructs the shell to read input from the current source until a line containing only delimiter (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input for a command.

The format of here-documents is:

      <<[-]word
              here-document
      delimiter

No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `.

If the redirection operator is <<-, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion.


1

在heredocs中,紧跟着<<的内容必须完全按照所示呈现以结束heredoc。

在你的情况下,缩进引入了制表符(或可能是空格),而 heredoc 分界符 END_SCRIPT 不能再被视为分界符。因此,sftp 命令继续寻找一个从未找到的分界符。

以下是格式。

command <<HEREDOC_DELIM

HEREDOC_DELIM 
# Note that nothing should be put in front of HEREDOC_DELIM - no indents.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接