Kiran Reddy
Kiran Reddy

Reputation: 13

If a file or directory exist then overwrite

I am new to shell scripting. If a file or directory (folder) exists then the script should overwrite it; if it doesn't exist then it should create a new file or directory.

This is what I have tried:

#!/bin/bash
unset File
unset Directory
echo -n "File:"
read File
echo -n "Directory:"
read Directory

if [ -f "$File" ]; then
    echo "file $File exist. Do you want overwrite it? (y/n)" 
    read yn                                              
    if [ $yn = "N" -o $yn = "n"];
    then
        exit 0
    fi
    echo "$File" >> testfile
else
    echo "file Does not exist"      
    touch $File
fi

if [ -d "$Directory" ]; then
    echo "directory $directory exist.Do you want overwrite it? (y/n)"
    read yn
    if [ $yn = "N" -o $yn = "n" ];
    then
        exit 0
    else
        echo "directory Does not exist"     
        mkdir -p  $Directory
    fi
fi    

What changes do I need to make to get the desired behaviour?

Upvotes: 0

Views: 2250

Answers (1)

ramana_k
ramana_k

Reputation: 1933

echo "$File" >> testfile

The above line 'appends' to a file named 'testfile'. It does not overwrite the file in question, which is $File.

if [ -d "$Directory" ]; then

    if [ $yn = "N" -o $yn = "n" ];
    then
        exit 0
    else

    fi
fi   

In this part, you need to add an 'else' clause to outer if, not the inner one to handle the case of directory not existing. Moreover '[ -d "$Directory" ]' test returns false if there is a normal file with the name '$Directory'. In that case, an attempt to create a directory with the same name fails.

Upvotes: 2

Related Questions