374

How can I write data to a text file automatically by shell scripting in Linux?

I was able to open the file. However, I don't know how to write data to it.

1

13 Answers 13

599

The short answer:

echo "some data for the file" >> fileName

However, echo doesn't deal with end of line characters (EOFs) in an ideal way. So, if you're going to append more than one line, do it with printf:

printf "some data for the file\nAnd a new line" >> fileName

The >> and > operators are very useful for redirecting output of commands, they work with multiple other bash commands.

Sign up to request clarification or add additional context in comments.

9 Comments

What is the name of this operator? I would like to find a manual about it.
the operator > redirects output to a file overwriting the file if one exists. The >> will append to an existing file.
Thank you, here is the link to wiki page, in case somebody needs it en.wikipedia.org/wiki/…
If you need to do this with root privileges, do it this way: sudo sh -c 'echo "some data for the file" >> fileName'
What if my text is something like this and for any reason, I can't use curl or wget?
|
180
#!/bin/sh

FILE="/path/to/file"

/bin/cat <<EOM >$FILE
text1
text2 # This comment will be inside of the file.
The keyword EOM can be any text, but it must start the line and be alone.
 EOM # This will be also inside of the file, see the space in front of EOM.
EOM # No comments and spaces around here, or it will not work.
text4 
EOM

5 Comments

Nice take on multiline output.
Newbies would benefit from knowing exactly what to do with this file. How to save it, how to run it, etc.
Please explain rather than simply putting up a piece of code. It would make it so much more helpful to everyone — especially newbies.
In this case scripts with variables like $some_var get lost. How can it be fixed?
77

You can redirect the output of a command to a file:

$ cat file > copy_file

or append to it

$ cat file >> copy_file

If you want to write directly the command is echo 'text'

$ echo 'Hello World' > file

1 Comment

If you need root permission: sudo sh -c 'cat file > /etc/init/gunicorn.conf' (thanks to lukaserat's comment above)
68
#!/bin/bash

cat > FILE.txt <<EOF

info code info 
info code info
info code info

EOF 

5 Comments

An explanation of your code would go a long way toward making it more usable to others. Even callouts of vocabulary like "here document" and "redirection" can point searchers to other resources.
Explanation is not so necessary for something like this.
Explanation is never necessary when you already know the answer. To me the above code is not helpful due to lack of details.
After EOF - should be no spaces.
35

I know this is a damn old question, but as the OP is about scripting, and for the fact that google brought me here, opening file descriptors for reading and writing at the same time should also be mentioned.

#!/bin/bash

# Open file descriptor (fd) 3 for read/write on a text file.
exec 3<> poem.txt

    # Let's print some text to fd 3
    echo "Roses are red" >&3
    echo "Violets are blue" >&3
    echo "Poems are cute" >&3
    echo "And so are you" >&3

# Close fd 3
exec 3>&-

Then cat the file on terminal

$ cat poem.txt
Roses are red
Violets are blue
Poems are cute
And so are you

This example causes file poem.txt to be open for reading and writing on file descriptor 3. It also shows that *nix boxes know more fd's then just stdin, stdout and stderr (fd 0,1,2). It actually holds a lot. Usually the max number of file descriptors the kernel can allocate can be found in /proc/sys/file-max or /proc/sys/fs/file-max but using any fd above 9 is dangerous as it could conflict with fd's used by the shell internally. So don't bother and only use fd's 0-9. If you need more the 9 file descriptors in a bash script you should use a different language anyways :)

Anyhow, fd's can be used in a lot of interesting ways.

Comments

20

I like this answer:

cat > FILE.txt <<EOF

info code info 
...
EOF

but would suggest cat >> FILE.txt << EOF if you want just add something to the end of the file without wiping out what is already exists

Like this:

cat >> FILE.txt <<EOF

info code info 
...
EOF

1 Comment

Add some explanation with answer for how this answer help OP in fixing current issue
13

For environments where here documents are unavailable (Makefile, Dockerfile, etc) you can often use printf for a reasonably legible and efficient solution.

printf '%s\n' '#!/bin/sh' '# Second line' \
    '# Third line' \
    '# Conveniently mix single and double quotes, too' \
    "# Generated $(date)" \
    '# ^ the date command executes when the file is generated' \
    'for file in *; do' \
    '    echo "Found $file"' \
    'done' >outputfile

1 Comment

Your comment above Try echo "some data for the file" | sudo tee -a fileName >/dev/null to only run tee as root. was really useful !
11

Moving my comment as an answer, as requested by @lycono

If you need to do this with root privileges, do it this way:

sudo sh -c 'echo "some data for the file" >> fileName'

1 Comment

You might want to avoid running a root shell just for printing a string. Try echo "some data for the file" | sudo tee -a fileName >/dev/null to only run tee as root.
11

I thought there were a few perfectly fine answers, but no concise summary of all possibilities; thus:

The core principal behind most answers here is redirection. Two are important redirection operators for writing to files:

Redirecting Output:

echo 'text to completely overwrite contents of myfile' > myfile

Appending Redirected Output

echo 'text to add to end of myfile' >> myfile

Here Documents

Others mentioned, rather than from a fixed input source like echo 'text', you could also interactively write to files via a "Here Document", which are also detailed in the link to the bash manual above. Those answers, e.g.

cat > FILE.txt <<EOF` or `cat >> FILE.txt <<EOF

make use of the same redirection operators, but add another layer via "Here Documents". In the above syntax, you write to the FILE.txt via the output of cat. The writing only takes place after the interactive input is given some specific string, in this case 'EOF', but this could be any string, e.g.:

cat > FILE.txt <<'StopEverything'` or `cat >> FILE.txt <<'StopEverything'

would work just as well. Here Documents also look for various delimiters and other interesting parsing characters, so have a look at the docs for further info on that.

Here Strings

A bit convoluted, and more of an exercise in understanding both redirection and Here Documents syntax, but you could combine Here Document style syntax with standard redirect operators to become a Here String:

Redirecting Output of cat Input

cat > myfile <<<'text to completely overwrite contents of myfile'

Appending Redirected Output of cat Input

cat >> myfile <<<'text to completely overwrite contents of myfile'

Comments

3

This approach works and is the best

cat > (filename) <<EOF
Text1...
Text2...
EOF

Basically the text will search for keyword "EOF" till it terminates writing/appending the file

1 Comment

This just repeats the previous answer from 2013.
2

If you are using variables, you can use

first_var="Hello"
second_var="How are you"

If you want to concat both string and write it to file, then use below

echo "${first_var} - ${second_var}" > ./file_name.txt

Your file_name.txt content will be "Hello - How are you"

1 Comment

Please share more details to your answer such that others can learn from it
1

Can also use here document and vi, the below script generates a FILE.txt with 3 lines and variable interpolation

VAR=Test
vi FILE.txt <<EOFXX
i
#This is my var in text file
var = $VAR
#Thats end of text file
^[
ZZ
EOFXX

Then file will have 3 lines as below. "i" is to start vi insert mode and similarly to close the file with Esc and ZZ.

#This is my var in text file
var = Test
#Thats end of text file

1 Comment

Note this same method using "cat" instead of "vi" as mentioned in other answers would be less extra typing.
0

If you want to write code at organization level you can use below code. Checking for errors is the key. In below case check if file exists.

#!/bin/bash
# Define constants
readonly FILE_NAME="output.txt"
# Function to check if the file exists
check_file_existence() {
    if [ -f "$1" ]; then
        echo "File $1 already exists."
        exit 1
    fi
}
# Main function
main() {
    check_file_existence "$FILE_NAME"
    echo "Enter some data:"
    read -r inputData
    echo "$inputData" > "$FILE_NAME"
    echo "Data has been written to $FILE_NAME"
}
# Call the main function
main

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.