I have a very long string to be printed by echo
command. By doing so I want it to be perfectly indented.
I am trying this and it is perfectly working fine
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
But as I try to indent it properly as the echo statement is also indented. It adds an extra space.
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
I can't find any working response which will do this perfectly.
The problem here is that you are giving two arguments to echo
, and its default behaviour is to prints them back with a space in between:
$ echo "a" "b"
a b
$ echo "a" "b"
a b
$ echo "a"\
> "b"
a b
If you want to have full control on what you are printing, use arrays with printf
:
lines=("This is a very long string. An"
"d it is printed in one line")
printf "%s" "${lines[@]}"
printf "\n"
This will return:
This is a very long string. And it is printed in one line
Or as suggested by 123 in comments, use echo
also with the array setting IFS to 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
From the Bash manual → 3.4.2. Special Parameters:
*
($) Expands to the positional parameters, starting from one. When the expansion is not within double quotes, each positional parameter expands to a separate word. In contexts where it is performed, those words are subject to further word splitting and pathname expansion. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$" is equivalent to "$1c$2c…", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
Interesting reading: Why is printf better than echo?.
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