bash – 用空格缩进heredocs

前端之家收集整理的这篇文章主要介绍了bash – 用空格缩进heredocs前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对于个人开发和项目,我使用四个空格而不是标签.
但是,我需要使用heredoc,我不能这样做,而不会破坏缩进流程.

我可以想到的唯一的工作方式是这样的:

  1. usage() {
  2. cat << ' EOF' | sed -e 's/^ //';
  3. Hello,this is a cool program.
  4. This should get unindented.
  5. This code should stay indented:
  6. something() {
  7. echo It works,yo!;
  8. }
  9. That's all.
  10. EOF
  11. }

有没有更好的方法来做到这一点?

让我知道这是否属于Unix/Linux Stack Exchange.

(如果您使用bash 4,请滚动到最后,我认为是纯shell和可读性的最佳组合.)

对于shell脚本,使用选项卡不是偏好或风格的问题;这是语言的定义.

  1. usage () {
  2. # Lines between EOF are each indented with the same number of tabs
  3. # Spaces can follow the tabs for in-document indentation
  4. cat <<-EOF
  5. Hello,this is a cool program.
  6. This should get unindented.
  7. This code should stay indented:
  8. something() {
  9. echo It works,yo!;
  10. }
  11. That's all.
  12. EOF
  13. }

另一个选择是避免使用这些文档,而不必使用更多的引号和行延续:

  1. usage () {
  2. printf '%s\n' \
  3. "Hello,this is a cool program." \
  4. "This should get unindented." \
  5. "This code should stay indented:" \
  6. " something() {" \
  7. " echo It works,yo!" \
  8. " }" \
  9. "That's all."
  10. }

如果您愿意放弃POSIX兼容性,可以使用数组来避免显式的行延续:

  1. usage () {
  2. message=(
  3. "Hello,this is a cool program."
  4. "This should get unindented."
  5. "This code should stay indented:"
  6. " something() {"
  7. " echo It works,yo!"
  8. " }"
  9. "That's all."
  10. )
  11. printf '%s\n' "${message[@]}"
  12. }

以下再次使用这里的文档,但这次用bash 4的readarray命令来填充数组.参数扩展从每个谎言的开始处理去除固定数量的空格.

  1. usage () {
  2. # No tabs necessary!
  3. readarray message <<' EOF'
  4. Hello,yo!;
  5. }
  6. That's all.
  7. EOF
  8. # Each line is indented an extra 8 spaces,so strip them
  9. printf '%s' "${message[@]# }"
  10. }

最后一个变体:您可以使用扩展模式来简化参数扩展.而不必计算用于缩进的空格数量,只需用选定的非空格字符结束缩进,然后匹配固定的前缀.我用 :. (下面的空格
冒号是为了可读性;它可以删除与前缀模式稍微改变.)

(另外,除此之外,您使用以白色开头的文档定界符的非常好的方法的一个缺点是它阻止您在文档中执行扩展,如果要这样做,您可以要么将分隔符保留为未绑定,或者对您的无标签规则造成一个小小的例外,请使用< -EOF和制表符缩进的关闭分隔符.)

  1. usage () {
  2. # No tabs necessary!
  3. closing="That's all"
  4. readarray message <<EOF
  5. : Hello,this is a cool program.
  6. : This should get unindented.
  7. : This code should stay indented:
  8. : something() {
  9. : echo It works,yo!;
  10. : }
  11. : $closing
  12. EOF
  13. shopt -s extglob
  14. printf '%s' "${message[@]#+( ): }"
  15. shopt -u extglob
  16. }

猜你在找的Bash相关文章