Prompt overwrite file in echo
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.
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 text
Or 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