Home > Net >  Writing to a file during a script
Writing to a file during a script

Time:04-02

I need to create and write a file in the middle of a script. Is there a way to do this? Usually, to create and write to a file, I would use cat >file name, then write what I needed and ctrl d to save and exit. However, I won't be able to ctrl d in the script to use cat >. What would I use?

CodePudding user response:

There are several options. For instance

>file_name

ensures that you have afterwards an empty file named file_name. If you write instead

touch file_name

then file_name will only be generated if it did not exist before. If it existed, it gets its time stamp updated.

You can also do a

[ -f file_name ] || touch file_name

This would generate file_name, if it did not exist, but leave the time stamp unchanged if the file existed already.

You can also fill the file with information contained in your script, by using a so-called here-document:

cat >file_name <<'END_OF_THE_WORLD'
Hello
$PATH
Goodbye
END_OF_THE_WORLD

The single quotes ensure that your file really contains the literal string $PATH, i.e. no parameter expansion is performed on the text.

CodePudding user response:

You could use:

echo "file content" > file.txt

Or, if you want to see the content while writing the file:

echo "file content" | tee file.txt
  • Related