This

STR="Hello\nWorld"
echo $STR

作为输出产生

Hello\nWorld

而不是

Hello
World

我应该做什么有一个换行在字符串?

注意:此问题与echo无关。 我知道echo -e,但我正在寻找一种解决方案,允许传递一个字符串(其中包括换行符)作为参数到其他命令,没有类似的选项来解释\n的换行符。


当前回答

我对这里的选择都不太满意。这对我来说很管用。

str=$(printf "%s" "first line")
str=$(printf "$str\n%s" "another line")
str=$(printf "$str\n%s" "and another line")

其他回答

我根据其他答案所做的是

NEWLINE=$'\n'
my_var="__between eggs and bacon__"
echo "spam${NEWLINE}eggs${my_var}bacon${NEWLINE}knight"

# which outputs:
spam
eggs__between eggs and bacon__bacon
knight

Echo是90年代的,而且充满了危险,使用它应该会导致内核转储不少于4GB。严肃地说,echo的问题是Unix标准化进程最终发明printf实用程序的原因,它解决了所有问题。

要在字符串中获取换行符,有两种方法:

# 1) Literal newline in an assignment.
FOO="hello
world"
# 2) Command substitution.
BAR=$(printf "hello\nworld\n") # Alternative; note: final newline is deleted
printf '<%s>\n' "$FOO"
printf '<%s>\n' "$BAR"

在那里!没有SYSV和BSD的回声疯狂,所有东西都被整齐地打印出来,并完全支持C转义序列。请大家现在就使用printf来满足所有的输出需求,不要回头。

如果你正在使用Bash,你可以在一个特别引用的$'string'中使用反斜杠转义。例如,添加\n:

STR=$'Hello\nWorld'
echo "$STR" # quotes are required here!

打印:

Hello
World

如果你使用的是其他shell,只需在字符串中插入换行符:

STR='Hello
World'

Bash在$ "字符串中识别出许多其他反斜杠转义序列。以下是Bash手册页面的节选:

Words of the form $'string' are treated specially. The word expands to
string, with backslash-escaped characters replaced as specified by the
ANSI C standard. Backslash escape sequences, if present, are decoded
as follows:
      \a     alert (bell)
      \b     backspace
      \e
      \E     an escape character
      \f     form feed
      \n     new line
      \r     carriage return
      \t     horizontal tab
      \v     vertical tab
      \\     backslash
      \'     single quote
      \"     double quote
      \nnn   the eight-bit character whose value is the octal value
             nnn (one to three digits)
      \xHH   the eight-bit character whose value is the hexadecimal
             value HH (one or two hex digits)
      \cx    a control-x character

The expanded result is single-quoted, as if the dollar sign had not
been present.

A double-quoted string preceded by a dollar sign ($"string") will cause
the string to be translated according to the current locale. If the
current locale is C or POSIX, the dollar sign is ignored. If the
string is translated and replaced, the replacement is double-quoted.

我发现-e标志优雅而直接

bash$ STR="Hello\nWorld"

bash$ echo -e $STR
Hello
World

如果字符串是另一个命令的输出,我只使用引号

indexes_diff=$(git diff index.yaml)
echo "$indexes_diff"

免责声明:我首先写了这篇文章,然后偶然发现了这个问题。我以为这个解决方案还没有发布,看到tlwhitec确实发布了一个类似的答案。我仍然把这个贴出来,因为我希望这是一个有用和彻底的解释。

简短的回答:

这似乎是一个相当可移植的解决方案,因为它可以在相当多的shell上工作(参见评论)。 通过这种方式,可以在变量中获得真正的换行符。

这种解决方案的好处是您不必在源代码中使用换行符,因此可以缩进 按照您想要的方式编写代码,解决方案仍然有效。这使得它健壮。它也很便携。

# Robust way to put a real newline in a variable (bash, dash, ksh, zsh; indentation-resistant).
nl="$(printf '\nq')"
nl=${nl%q}

再答:

以上方案说明:

换行符通常会因为命令替换而丢失,但是为了防止这种情况,我们添加了一个'q',然后删除它。(使用双引号的原因将在下文进一步解释。)

我们可以证明变量包含一个实际的换行符(0x0A):

printf '%s' "$nl" | hexdump -C
00000000  0a  |.|
00000001

(请注意,'%s'是需要的,否则printf将把文字'\n'字符串转换为实际的0x0A字符,这意味着我们什么也证明不了。)

当然,除了这个答案中提出的解决方案,人们也可以使用这个(但是…):

nl='
'

... 但是这种方法的健壮性较差,并且很容易因为不小心缩进代码,或者后来忘记缩进代码而被破坏,这使得在(缩进的)函数中使用不方便,而早期的解决方案是健壮的。

Now, as for the double quotes: The reason for the double quotes " surrounding the command substitution as in nl="$(printf '\nq')" is that you can then even prefix the variable assignment with the local keyword or builtin (such as in functions), and it will still work on all shells, whereas otherwise the dash shell would have trouble, in the sense that dash would otherwise lose the 'q' and you'd end up with an empty 'nl' variable (again, due to command substitution). That issue is better illustrated with another example:

dash_trouble_example() {
    e=$(echo hello world) # Not using 'local'.
    echo "$e" # Fine. Outputs 'hello world' in all shells.

    local e=$(echo hello world) # But now, when using 'local' without double quotes ...:
    echo "$e" # ... oops, outputs just 'hello' in dash,
              # ... but 'hello world' in bash and zsh.

    local f="$(echo hello world)" # Finally, using 'local' and surrounding with double quotes.
    echo "$f" # Solved. Outputs 'hello world' in dash, zsh, and bash.

    # So back to our newline example, if we want to use 'local', we need
    # double quotes to surround the command substitution:
    # (If we didn't use double quotes here, then in dash the 'nl' variable
    # would be empty.)
    local nl="$(printf '\nq')"
    nl=${nl%q}
}

上述解决方案的实际示例:

# Parsing lines in a for loop by setting IFS to a real newline character:

nl="$(printf '\nq')"
nl=${nl%q}

IFS=$nl

for i in $(printf '%b' 'this is line 1\nthis is line 2'); do
    echo "i=$i"
done

# Desired output:
# i=this is line 1
# i=this is line 2

# Exercise:
# Try running this example without the IFS=$nl assignment, and predict the outcome.