Prompt overwrite file in echo
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.txtAnd 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: 2 Answers
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 noclobberExample:
$ echo "new text" > existing_file.txt
$ set -o noclobber
$ echo "another text" > existing_file.txt
bash: existing_file.txt: cannot overwrite existing fileTo unset the option:
set +o noclobberYou 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
y
$ cat testfile
new textOr turn that into a script:
$> ./confirm_overwrite.sh "testfile" "some string"
File exists. Overwrite? y/n
y
$> ./confirm_overwrite.sh "testfile" "some string"
File exists. Overwrite? y/n
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" ;; esac
else # file doesn't exist or no write permission granted # will fail if no permission to write granted echo "$2" > "$1"
fi