2

How can I pipe the output of a program or function into a variable?

For example lets say I have this script:

function foobarize () {
    sed \
    -e "s|${foo}|${bar}|g" \
    $1
}

echo foo | foobarize | set THIS_VARIABLE

Obviously it won't work to set the value of THIS_VARIABLE.

But if I do:

THIS_VARIABLE=$(echo foo | foobarize)

... that doesn't work either because it strips any trailing newlines.

So how do I get the output of foobarize into THIS_VARIABLE without using back-ticks or $() ?

2

You can do the thing you said:

THIS_VARIABLE=$(echo foo| foobarize; printf .)
THIS_VARIABLE=${THIS_VARIABLE%.}

That won't strip any trailing newlines. With a little more information about the purpose behind saving THIS_VARIABLE and I may be able to help further.

Some examples:

$ v=$(printf '0123456789' | sed -n p; printf .)
$ printf %s "${v%?}" | wc
0       1       10

$ v=$(printf '\n\n\n\n\n\n\n\n' | sed -n p; printf .)
$ printf %s "${v%?}" | wc
8       0       8

See?

  • I thought the $() syntax will strip trailing whitespaces. Also why did you do { foobarize; printf .; } instead of just foobarize? The purpose of THIS_VARIABLE is to check its last character to make sure no whitespace was stripped! – CommaToast Sep 9 '14 at 5:56
  • @CommaToast - no whitespace is stripped - it's all there. printf just adds a single dot, the stdin from the pipe still goes to foobarize. But printf doesn't do anything until foobarize has already handled its in/out and completed. But you're right - I didn't need the group there. – mikeserv Sep 9 '14 at 5:59
  • @CommaToast - it will strip trailing newlines. But it won't strip newlines that don't trail. So \n\n\n\n\n\n\n\n\n. is fine. After you set the variable to that value, then you just remove the dot. Is there something I can explain better? – mikeserv Sep 9 '14 at 6:08
  • I just want to be able to have a file come in and out of this script and not have its newline messed with. If it has one then it should stay there. If it lacks one then it should not have one added. I'm having trouble with this. – CommaToast Sep 9 '14 at 6:14
  • @CommaToast - If you do ^this^ - that's what you get. This also removes sed's extra newline. Test it, man. If there's some way I can explain it better, I'd really like to. Maybe I'll do some visual stuff. Hang on a minute. – mikeserv Sep 9 '14 at 6:15

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.