To write to a file and overwrite any existing data, you can use the
> operator. For example, to write “Hello, world!” to a file called
hello.txt, you can run the following command:
>> helps to append, but you can use a single arrow syntax to overwrite existing data.
echo "Hello, world!" > hello.txt
If the file
hello.txt already exists, this command will overwrite its contents with “Hello, world!”. If the file does not exist, it will be created and then populated with “Hello, world!”.
Note: Most Linux shells(bash, csh, ksh, tcsh) have a built-in file protection mechanism to prevent files from being overwritten accidentally. So if noclobber is enabled the above command won’t work for you.
In that event, you need to use the code below. Note the pipe symbol after the redirection.
echo "Hello, world!" >| hello.txt
Run the below command to see if noclobber is enabled.
set -o | grep noclobber