当分割成多行时,如何避免回声中的空格

mol*_*ule 7 linux bash shell

我有一个很长的字符串要通过echo命令打印.通过这样做,我希望它完美缩进.我正在尝试这个,它完美地工作

echo "This is a very long string. An"\
"d it is printed in one line"

Output:
This is a very long string. And it is printed in one line
Run Code Online (Sandbox Code Playgroud)

但是当我尝试缩进它时,因为echo语句也是缩进的.它增加了额外的空间.

echo "This is a very long string. An"\
    "d it is printed in one line"

Output:
This is a very long string. An d it is printed in one line
Run Code Online (Sandbox Code Playgroud)

我找不到任何可以完美做到这一点的工作回应.

fed*_*qui 6

这里的问题是你给两个参数echo,它的默认行为是打印它们,中间有一个空格:

$ echo "a"             "b"
a b
$ echo "a" "b"
a b
$ echo "a"\
>           "b"
a b
Run Code Online (Sandbox Code Playgroud)

如果要完全控制要打印的内容,请使用以下数组printf:

lines=("This is a very long string. An"
       "d it is printed in one line")
printf "%s" "${lines[@]}"
printf "\n"
Run Code Online (Sandbox Code Playgroud)

这将返回:

This is a very long string. And it is printed in one line
Run Code Online (Sandbox Code Playgroud)

或者如评论中123建议的那样,echo也可以使用数组设置IFS为null:

# we define the same array $lines as above

$ IFS=""
$ echo "${lines[*]}"
This is a very long string. And it is printed in one line
$ unset IFS
$ echo "${lines[*]}"
This is a very long string. An d it is printed in one line
#                             ^
#                             note the space
Run Code Online (Sandbox Code Playgroud)

Bash手册→3.4.2.特殊参数:

*

($ )从1开始扩展到位置参数.当扩展不在双引号内时,每个位置参数都会扩展为单独的单词.在执行它的上下文中,这些单词受到进一步的单词拆分和路径名扩展的影响.当扩展发生在双引号内时,它会扩展为单个单词,每个参数的值由IFS特殊变量的第一个字符分隔.也就是说,"$ "相当于"$ 1c $ 2c ...",其中c是IFS变量值的第一个字符.如果未设置IFS,则参数由空格分隔.如果IFS为null,则连接参数时不会插入分隔符.

有趣的阅​​读:为什么printf比echo更好?.

  • @molecule for echo你只需将IFS更改为空,然后使用`$ {lines [*]}打印数组. (2认同)