Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell script to remove a file if it already exist

Tags:

shell

People also ask

How do you remove file if it exists in Unix?

Example-1: Delete the file using `rm` command without the option. You can apply the 'rm' command to remove an existing file. In the following script, an empty file is created by using the 'touch' command to test 'rm' command. Next, 'rm' command is used to remove the file, test.

How do I delete a file in Bash?

To delete a specific file, you can use the command rm followed by the name of the file you want to delete (e.g. rm filename ). For example, you can delete the addresses. txt file under the home directory.

How do you delete a file if already exists in Java?

files. deleteifexists(Path p) method defined in Files package: This method deletes a file if it exists. It also deletes a directory mentioned in the path only if the directory is not empty. Returns: It returns true if the file was deleted by this method; false if it could not be deleted because it did not exist.


Don't bother checking if the file exists, just try to remove it.

rm -f /p/a/t/h
# or
rm /p/a/t/h 2> /dev/null

Note that the second command will fail (return a non-zero exit status) if the file did not exist, but the first will succeed owing to the -f (short for --force) option. Depending on the situation, this may be an important detail.

But more likely, if you are appending to the file it is because your script is using >> to redirect something into the file. Just replace >> with >. It's hard to say since you've provided no code.

Note that you can do something like test -f /p/a/t/h && rm /p/a/t/h, but doing so is completely pointless. It is quite possible that the test will return true but the /p/a/t/h will fail to exist before you try to remove it, or worse the test will fail and the /p/a/t/h will be created before you execute the next command which expects it to not exist. Attempting this is a classic race condition. Don't do it.


Another one line command I used is:

[ -e file ] && rm file

You can use this:

#!/bin/bash

file="file_you_want_to_delete"

if [ -f "$file" ] ; then
    rm "$file"
fi

If you want to ignore the step to check if file exists or not, then you can use a fairly easy command, which will delete the file if exists and does not throw an error if it is non-existing.

 rm -f xyz.csv