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:

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


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


Use test command (which is aliased by square brackets[ ) to see if file exists

$ if [ -w testfile  ]; then                                                                                               
> echo " Overwrite ? y/n "
> read ANSWER
> case $ANSWER in
>   [yY]) echo "new text" > testfile ;;
>   [nN]) echo "appending" >> testfile ;;
> esac
> fi  
 Overwrite ? y/n 

$ cat testfile
new text

Or turn that into a script:

$> ./confirm_overwrite.sh "testfile"  "some string"                                                                       
File exists. Overwrite? y/n
$> ./confirm_overwrite.sh "testfile"  "some string"                                                                       
File exists. Overwrite? y/n
OK, I won't touch the file
$> rm testfile                                                                                                            
$> ./confirm_overwrite.sh "testfile"  "some string"                                                                       
$> cat testfile
some string
$> cat confirm_overwrite.sh
if [ -w "$1" ]; then
   # File exists and write permission granted to user
   # show prompt
   echo "File exists. Overwrite? y/n"
   read ANSWER
   case $ANSWER in 
       [yY] ) echo "$2" > testfile ;;
       [nN] ) echo "OK, I won't touch the file" ;;
   # file doesn't exist or no write permission granted
   # will fail if no permission to write granted
   echo "$2" > "$1"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.