Ubuntu – Prompt overwrite file in echo

bashecho

I am writing to a file using simple echo (I'm open to using other methods).

When writing to a file that already exists, can I make echo prompt the user to overwrite or not?

For eg, maybe an argument like -i would work?

echo -i "new text" > existing_file.txt

And the desired outcome is to prompt the user to overwrite or not…

echo -i "new text" > existing_file.txt
Do you wish to overwrite 'existing_file.txt'? y or n:

Best Answer

The > redirection is done by shell, not by echo. In fact, the shell does the redirection before the command is even started and by default shell will overwrite any file by that name if exists.

You can prevent the overwriting by shell if any file exists by using the noclobber shell option:

set -o noclobber

Example:

$ echo "new text" > existing_file.txt

$ set -o noclobber 

$ echo "another text" > existing_file.txt
bash: existing_file.txt: cannot overwrite existing file

To unset the option:

set +o noclobber

You won't get any option like taking user input to overwrite any existing file, without doing something manual like defining a function and use it every time.

Related Question