2

I want to make the following commands:

cat > template.txt [enter in the terminal] text [Ctrl+d in the terminal]

in a script.

Is there a way to tell the script to do enter\Ctrl d? Is there a way to create a file and write to it in script?

I didn't find anything that worked for me.

Thanks.

Jameson
  • 6,400
  • 6
  • 32
  • 53
Gum Bi
  • 313
  • 2
  • 4
  • 11
  • This problem doesn't seem related to c. What script do you use? Bash? Zsh? Perl? Python? Ruby? Other? – MikeCAT Nov 01 '15 at 04:31
  • Related question [Representing EOF in C code?](https://stackoverflow.com/questions/12389518/representing-eof-in-c-code) – Trutane Mar 06 '18 at 23:16

3 Answers3

8

A Here Document is kind of like a script version of what you're talking about, I think, although it is not entirely clear to me from your description.

#!/bin/bash

cat > template.txt <<- EOF
    Here
    is some 
    text.
EOF

Ctrl-D itself is the EOF character, ASCII 4.

Jameson
  • 6,400
  • 6
  • 32
  • 53
  • 1
    Be careful with this construction because it is whitespace senstitive. http://askubuntu.com/questions/485567/unexpected-end-of-file – Herman Toothrot Aug 01 '16 at 13:58
1

When you want an interactieve user enter lines and add them to your file until the user enters an ^D you can use the next script:

echo "Please give input"

while read -r line; do
            echo "Enter next line or ^D"
            echo "${line}" >> template.txt
done
echo "After loop"

You do not have to check for ^D, that will be recognized by read without doing something extra.So you do not need to use CTRL-V CTRL-D in vi.

Walter A
  • 19,067
  • 2
  • 23
  • 43
0

No, there isn't. How should the script know when your user is finished entering text?

tink
  • 14,342
  • 4
  • 46
  • 50