Open and write data to text file using bash/shell

2019-01-06 09:00发布

问题:

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:

echo "some data for the file" >> fileName


回答2:

#!/bin/sh

FILE="/path/to/file"

/bin/cat <<EOM >$FILE
text1
text2
text3
text4
EOM


回答3:

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


回答4:

#!/bin/bash

cat > FILE.txt <<EOF

info code info 
info code info
info code info

EOF 


回答5:

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.



回答6:

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


回答7:

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'


回答8:

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


标签: bash shell