- Published on
How to delete File or Directory if it Exists in Bash or Zsh
- Authors
- Name
- Ashik Nesin
- @AshikNesin
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
fi
# For directory
if [ -d "node_modules" ]; then
rm -r node_modules
fi
Happy conditional deletes!