2

I have a bash script like

./script -a filename

And I have the content of a file in a variable $CONTENT

How can I pass the variable into the command. I mean I could write the content of the variable down to disk first, but that seems to be too much overhead.

Is there a better solution?

Something like

./scrip -a << $CONTENT

2 Answers 2

4

You need one more <:

./script -a <<<"$CONTENT"

<<< is called a herestring, and takes the following string and passes it as the standard input.

Sign up to request clarification or add additional context in comments.

5 Comments

You should use quotes: ./script -a <<< "$CONTENT"
You must be joking, and it's not funny! Try: s="a b" (with, say, three spaces between a and b, it doesn't show properly here), then compare cat <<< $s and cat <<< "$s". Also, please refer to the Here String section of the manual. You'll read: The word is expanded and supplied to the command on its standard input. Yes, is expanded. As a general rule: Use More Quotes!
I see, the spaces are collapsed. It doesn't expand into other arguments though, which is what I had tested.
Expansion for unquoted variables can have side effects, e.g., if you set funny IFS, etc. so better always quote!
I was trying to use that with xsltproc <<< "$xslt_content" "$xml_path" and file <<< "$content". None of those worked. Does it have to be the last argument? What's wrong with the file call?
4

Kevin's suggestion to use a here string will work, as long as you quote the variable as suggested in the comments to that answer. A more portable solution is to use a here doc:

./script -a << EOF
$CONTENT
EOF

In this case, quotes are not necessary and indeed undesirable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.