6

I am unable to figure out how to indent parts of bash script, preserving indentation in the code. I want the output to be formatted with correctly without any tabs/spaces prefix to the output lines.

ex: script

#!/bin/bash

INFO1="something
output1"
INFO2="output2"
MY_INFO=INFO1

if [ True ]; then
    INFO="
    Here are the test results
    bbb
    ccc
    aaa
    ${!MY_INFO}
    " 
fi
echo "${INFO}"

output returned:

    Here are the test results
    bbb
    ccc
    aaa
    something
output1

expected output:

Here are the test results
bbb
ccc
aaa
something
output1
Greg Petr
  • 1,099
  • 2
  • 11
  • 18
  • are you missing an `echo $INFO`? – meatspace Mar 27 '17 at 01:32
  • updated the question – Greg Petr Mar 27 '17 at 01:33
  • if you echo that double-quoted variable, it will print `$INFO` with the newlines and indent. if you echo it without the quotes you'll get it all on one line. If you want to `echo` something and have the output differ from that something, you'll have to strip the leading spaces with something like `sed`. – meatspace Mar 27 '17 at 01:36
  • 2
    This question has [already been asked](http://stackoverflow.com/a/23929367/7541976) before. – Varun Mar 27 '17 at 01:42
  • @Varun, The Q concerns indentation in the source code, and is therefore unlike *Multi-line string with extra space (preserved indentation)*, which has no indention in the source. – agc Mar 27 '17 at 02:57

1 Answers1

3

Quotes preserving spaces isn't a bug, it's a feature. It's what double quotes are for.

The other problem is that bash, (unlike python), doesn't know a thing about indenting for readability -- to bash one unquoted space is the same as a thousand.

Various remedies:

  1. Surrender indentation when multi-line strings are quoted, i.e.:

    if [ True ]; then
    INFO="
    Here are the test results
    bbb
    ccc
    aaa
    ${!MY_INFO}
    " 
    fi
    
  2. Use bash, (or some other tool), to make the indents go away. So first define an indented multi-line string:

     foo="
          bar
          baz"
    

    Then tweak $foo to remove spaces:

     foo="${foo// }"
    

    Now, $foo is no longer indented, but that would go too far if there are spaces that should have been kept.

  3. Same as before, but at display time, (this is more wasteful), i.e.:

    echo  "${foo// }"
    
agc
  • 7,973
  • 2
  • 29
  • 50