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
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:
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
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.
Same as before, but at display time, (this is more wasteful), i.e.:
echo "${foo// }"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With