【问题标题】:Return Status 1 for Assigning Heredoc to Variable through a function通过函数将 Heredoc 分配给变量的返回状态 1
【发布时间】:2012-06-06 03:30:26
【问题描述】:

这是将此处文档的内容分配给变量的一种方法。但是,它的执行将返回状态 1 而没有说明原因。

#! /bin/bash
# set -e -x

# This implementation returns 1
define(){ IFS='\n'; read -r -d '' ${1}; }
define thedoc <<'EOF'
Here is my here doc.
There was an ASCII banana here too,
but `read` would just it concatenate to mush.
EOF
# The here document will print with the following when `set -e` in not invoked.
echo $thedoc

只要set -e 已关闭,所有内容都会通过检查甚至执行进行检查。这不是上面的 Banana 独有的,而是上面 define() 构建的任何此处的文档。该错误从何而来?

【问题讨论】:

  • 我不确定它是什么意思,但是当我运行你的代码时,所有的 'n' 都被替换为 thedoc 值中的空格。
  • 这种行为是意料之中的。香蕉也许是个糟糕的选择。 :P

标签: bash shell variable-assignment


【解决方案1】:

当您使用空字符串作为read 的分隔符时,它基本上不会看到分隔符并遇到文件结尾,因此它将返回状态设置为1。您可以使用while read 循环来避免这种情况。

来自Bash Reference Manual

返回码为零,除非遇到文件结尾、read 超时(在这种情况下返回码大于 128),或者提供了无效的文件描述符作为 '@987654326 的参数@'。

另外,不要使用-e。使用显式错误处理。见BashFAQ/105

此外,为了保留空格、制表符和换行符而不是“连接成糊状”,您必须引用您 echo 的变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    相关资源
    最近更新 更多