Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove starting space tabs output echo multi-lined string

Tags:

bash

shell

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
like image 737
Greg Petr Avatar asked Oct 29 '22 10:10

Greg Petr


1 Answers

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// }"
    
like image 199
agc Avatar answered Nov 15 '22 13:11

agc