san1512
san1512

Reputation: 1023

Script to read contents from the user

How to write a shell script which creates a file

    echo "Enter the file you want to create"
    read a
    touch $a

And adds content to the created file 'a'

echo "Enter the contents to your $a file:"
cat > $a << 'EOF'
EOF

The above one is not the right way, what I am doing wrong here ?

Upvotes: 0

Views: 26

Answers (2)

John1024
John1024

Reputation: 113994

You were almost there. This will do what you ask:

echo "Enter the file you want to create"
read a
echo "Enter the contents to your $a file (press ctrl-D when done):"
cat >"$a"

Discussion

touch $a

It is not necessary to touch the file. The cat statement will create it regardless.

Also, because file names can include whitespace, it is best to put inside double-quotes any shell variable containing a file name. This prevents word splitting.

cat > $a << 'EOF'
EOF

The construct << 'EOF' tells the shell to read from a here document. This is what you use if you have text in your shell script that you want to use as input. You don't. You want instead to read input from the user. Thus the above two lines can be simply replaced with cat >"$a" .

Upvotes: 2

Cyrbil
Cyrbil

Reputation: 6478

You can ask then proceed with a simple echo:

echo "Enter the file you want to create"
read file
echo "Enter the contents to your $a file:"
read content

echo "$content" > "$file"

Upvotes: 1

Related Questions