Best Way to Print Here Documents Directly in Bash?

0
5
Asked By SillyPineapple92 On

I'm looking for an efficient method to print "Here documents" or "Here Strings" directly in Bash without having to save them to a variable or a file. I came across a snippet that uses `printf` and here-doc syntax: ```bash
{ printf "%sn" "$(< /dev/stdin)"; } <<-EOF
This is first line.
This is second line.
This is third line.
EOF
```
Is this the best approach, or are there better alternatives while strictly using Bash builtins?

3 Answers

Answered By QuickThinker3 On

If you want to utilize a builtin, you could enable a loadable one like `cat` using:
```bash
$ enable -f cat cat
$ cat <<EOF
Hello, world!
EOF
```
This way, you'll rule out the external command and just be using shell builtins!

Answered By BashNinja77 On

Make sure you're using `%sn` instead of `%sn`. It's a simple typo, but it could cause issues in your output. Just a heads-up!

Answered By CuriousCoder54 On

Using `cat` is common practice, but it’s not technically a Bash builtin. However, if you're looking to stick strictly to builtins, you can try this:
```bash
cat <<EOF
This is the first line.
This is the second line.
This is the third line.
EOF
```
Keep in mind you might not get the same output formatting without `printf`. Definitely worth a shot if you want an easy solution!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.