I know the question sounds to be discussed thousands times before. But somehow I can't find good solution.

Problem: I need to write multiline text from shell. The text might contain special chars sequences (starting from $) and I don't want to escape them. How to do this?

Currently I'm using cat:

cat <<TAGTEXTFILE > sometext.txt
Here is some text in which I don't want to escape sequences like: $().
I just want to see this text in this script exactly as 
it will look in resulting sometext.txt file.

But with cat I have to escape this: $(). How to write multiline text without escaping special characters? Please don't offer to use Python, I need shell solution (bash or dash).

  • 1
    What is your system ? i cannot reproduce your issue on mines (Ubuntu 12.04 and Debian 5). Copy/paste your code worked like a charm... – user2196728 Jan 1 '14 at 16:00
  • @user2196728 it works, but it wouldn't work if it had $PWD in it, for example. that's the point – Robin Green Jan 1 '14 at 16:01
  • Do you want $PWD to be expanded (like /home/vladimir/foo/) or not? – terdon Jan 1 '14 at 16:13
  • Yeah, exactly. My sample wasn't from real life, I just changed it. So '$()' appears in script but it doesn't in resulting text file. I understand why, I just don't need this functionality. In fact I do not want anything to be expanded, nor $PWD neither $(...) commands and still need to have convenient way to write multiline text. – vladimir Jan 1 '14 at 16:23
cat <<"TAGTEXTFILE" > sometext.txt
... some text ...
  • Wow! What a trick! How do you learn such things? Is it somewhere in man? – vladimir Jan 1 '14 at 16:26
  • it is in info bash. But generally when I want to know how to do something in bash I use Google, because the documentation is hard to navigate. – Robin Green Jan 1 '14 at 16:28
  • See the section of the man page under "Here documents". The relevant sentence is "If any characters in word are quoted, [...] the lines in the here-document are not expanded". – chepner Jan 2 '14 at 18:51

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.