Published on

How to delete File or Directory if it Exists in Bash or Zsh


When you delete a file or directory and if it does not exist then it'll throw an error in pretty much all the shells like Bash or Zsh.

We need to conditionally check them before performing the delete operation.

Here is how to do it.

# For file
if [ -f "package-lock.json" ]; then
  rm package-lock.json
# For directory
if [ -d "node_modules" ]; then
  rm -r node_modules

Happy conditional deletes!