【问题标题】:heredoc gives 'unexpected end of file' error [duplicate]heredoc 给出“文件意外结束”错误 [重复]
【发布时间】:2017-10-22 12:35:55
【问题描述】:

我正在 iOS X 上创建一个 Bash 脚本文件,询问用户是否愿意将文件上传到服务器。 sftp 命令(带定界符)在 if 语句之外工作正常,但是当我将 sftp 命令(带定界符)放在 if 语句中时,我收到以下错误消息:“upload.sh:line nnn:语法错误:意外结束文件”

printf "Upload file? [y]es?"
read -r input1
if [ $input1 == "y" ] || [ $input1 == "yes" ]; then
  sftp -i key.txt user@server << DELIMITER
    put local/path/to/file /server/upload/dir
    quit
  DELIMITER
fi

我在这里错过了什么?

【问题讨论】:

  • 不要缩进 heredoc 标记 (DELIMITER) 的末尾。通过 shellcheck.net 检查你的脚本。

标签: bash syntax heredoc


【解决方案1】:

heredoc 标记不应缩进(我假设您使用空格进行缩进)。用这种方式重写你的代码:

printf "Upload file? [y]es?"
read -r input1
if [ "$input1" == "y" ] || [ "$input1" == "yes" ]; then
  sftp -i key.txt user@server << DELIMITER
    put local/path/to/file /server/upload/dir
    quit
DELIMITER
fi

请务必将您的变量用双引号括起来,以防止因分词、通配符和空字符串破坏您的测试 ([ ... ]) 命令而引起的问题。


另见:

【讨论】:

  • 感谢@codeforester!我不知道heredoc 标记的缩进问题。
【解决方案2】:

如果你想在heredoc中使用TAB缩进,那么重定向操作符&lt;&lt;后面应该跟-(破折号),结果是&lt;&lt;-。然后将忽略heredoc 中的任何前导TAB

printf "Upload file? [y]es?"
read -r input1
if [ "$input1" = "y" ] || [ "$input1" = "yes" ]; then
    sftp -i key.txt user@server <<- DELIMITER
        put local/path/to/file /server/upload/dir
        quit
    DELIMITER
fi

另一种方法是简单的输入重定向,可以用来代替heredoc:

printf "Upload file? [y]es?"
read -r input1
if [ "$input1" = "y" ] || [ "$input1" = "yes" ]; then
  sftp -i key.txt user@server < \
  <(echo "put local/path/to/file /server/upload/dir ; quit")
fi 

也没有理由使用==;比较单括号内的字符串时,请改用=。如果使用双括号,则含义会发生变化,因此通常最好习惯性地使用它。

【讨论】:

    猜你喜欢
    • 2013-09-10
    • 2017-05-17
    • 2017-06-25
    • 2012-02-10
    • 2022-01-23
    • 2015-09-08
    • 1970-01-01
    • 2013-06-08
    相关资源
    最近更新 更多