Search code examples
bashshellnewlinecommand-substitution

Prepend printed string with its final newlines to a bash variable


I have the following function defined in bash:

function print_revision {
    printf "Revision %s (%s)\n%s\n\n" "$1" "$(date --utc +%d.%m.%Y,\ %H:%M\ UTC)" \
    "----------------------------------------"
}

I also have a variable, $CHANGES with some text in it. What I would need to do is prepend the string printed in print_revision to the $CHANGES variable.

I've tried the following but it doesn't seem to work:

CHANGES="$(print_revision $CURRENT_SHORT_REVISION)"$CHANGES

It prepends everything from print_revision but it goes through the last two newline characters, concatenating the contents of $CHANGES right after the ----- part.

How can I achieve what I need?


Solution

  • The simplest fix is to just print the current value of $CHANGES inside the command substitution:

    CHANGES="$(print_revision $CURRENT_SHORT_REVISION; echo "$CHANGES")"