Open and write data to text file using Bash?

BashShell

Bash Problem Overview


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.

Bash Solutions


Solution 1 - Bash

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 gonna 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.

Solution 2 - Bash

#!/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

Solution 3 - Bash

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

Solution 4 - Bash

#!/bin/bash

cat > FILE.txt <<EOF

info code info 
info code info
info code info

EOF 

Solution 5 - Bash

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.

Solution 6 - Bash

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

Solution 7 - Bash

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'

Solution 8 - Bash

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

Solution 9 - Bash

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'

Solution 10 - Bash

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"

Solution 11 - Bash

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

Solution 12 - Bash

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdnanView Question on Stackoverflow
Solution 1 - BashRocky PulleyView Answer on Stackoverflow
Solution 2 - BashcoolfireView Answer on Stackoverflow
Solution 3 - BashssedanoView Answer on Stackoverflow
Solution 4 - BashbaetacosView Answer on Stackoverflow
Solution 5 - BashtobiView Answer on Stackoverflow
Solution 6 - BashMaratView Answer on Stackoverflow
Solution 7 - BashlukaseratView Answer on Stackoverflow
Solution 8 - BashtripleeeView Answer on Stackoverflow
Solution 9 - Bashtopher217View Answer on Stackoverflow
Solution 10 - Bashbhargav3vediView Answer on Stackoverflow
Solution 11 - BashRajeevView Answer on Stackoverflow
Solution 12 - BashSubodh SharmaView Answer on Stackoverflow