Say I have these Bash commands:

$ sha="$(git log --all --format=format:%H -n 1 -- .npp.json)"
$ git branch  --contains "$sha" | tr -d " *"

right now that might log something like:


my question is - is there some Bash utility that can concatenate all the output for me, so that I get something like this:


the utility might look like:

$ git branch  --contains "$sha" | tr -d " *" | concat ":"

of course the final value would need to be echoed, so it might look like:

$ result="$(git branch  --contains "$sha" | tr -d " *" | concat ":")"
$ echo "$result"

If you're asking how to change




then tr '\n' : would be the classical UNIXy way to do it.

As for trimming a possible final newline, you could save the output to a variable first via $() and the $() will remove it, or you can do the substitution, save the result in a variable and then do variable=${variable%:} to trim it the final colon. (See https://stackoverflow.com/questions/1654021/how-can-i-delete-a-newline-if-it-is-the-last-character-in-a-file for more options.)

  • thanks, I improved the title of the OP (I think), looks like your solution works – Alexander Mills Aug 12 '18 at 23:43
  • what about trimming any extra whitespace? I like to be very sure lulz – Alexander Mills Aug 12 '18 at 23:55
  • @AlexanderMills Mentioned two ways you can get rid of it. – PSkocik Aug 13 '18 at 0:03
  • 1
    If you're going to do a command substitution + parameter substitution, you could consider using parameter substitution in place of tr to do the replacement e.g. var=$(git branch . . . ) ; var="${var//$'\n'/:}" – steeldriver Aug 13 '18 at 1:07
  • @steeldriver Good point. There's definitely many other ways to do this. I just generally try to avoid non-POSIX stuff in shell answers (the feature you mention is a bashism/kshism). – PSkocik Aug 13 '18 at 1:11

For my use case, splitting on whitespace characters will work, since git branches cannot contain whitespace chars.

So I can do this:

git branch  --contains "$sha" | tr -d " *" | xargs

but for a generic solution, it would help to be able to control what the delimiting character was, so I don't really consider xargs used above, to be a good generic solution.

  • 1
    ... in that case you could replace xargs by paste -sd : I think – steeldriver Aug 12 '18 at 23:04
  • oh got it, how does that compare with the tr solution by @PSkocik – Alexander Mills Aug 12 '18 at 23:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.