Create , Write and Save file from a Shell script

I don't want to write the file manually, so I made a shell-script. Is there a way to write & save the file automatically without getting the user to press keys?

sudo nano blah
#write stuff to file
#save file
#continue

^ This will be inside a *.sh file

Or is there another way to create a simple text file in a script?

4

2 Answers

For more complex sequences of commands you should consider using the cat command with a here document. The basic format is

command > file << END_TEXT
some text here
more text here
END_TEXT

There are two subtly different behaviors depending whether the END_TEXT label is quoted or unquoted:

  1. unquoted label: the contents are written after the usual shell expansions

  2. quoted label: the contents of the here document are treated literally, without the usual shell expansions

For example consider the following script

#!/bin/bash
var1="VALUE 1"
var2="VALUE 2"
cat > file1 << EOF1
do some commands on "$var1"
and/or "$var2"
EOF1
cat > file2 << "EOF2"
do some commands on "$var1"
and/or "$var2"
EOF2

The results are

$ cat file1
do some commands on "VALUE 1"
and/or "VALUE 2"

and

$ cat file2
do some commands on "$var1"
and/or "$var2"

If you are outputting shell commands from your script, you probably want the quoted form.

2

There is no need to mess about with an editor to do this.

You can append something to a file with a simple echo command. For example

echo "Hello World" >> txt

Will append "Hello world" to the the file txt. if the file does not exist it will be created.

Or if the file may already exist and you want to overwrite it

echo "Hello World" > txt

For the first line: and

echo "I'm feeling good" >> txt
echo "how are you" >> txt 

For subsequent lines.

At it's simplest the .sh script could just contain a set of echo commands.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like