Deleting Matched Files

Powerful Command-Line Applications in Go — by Ricardo Gerardi (42 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Testing with Table-Driven T esting | TOC | Testing with the Help of T est Helpers 👉

Let’s make the walk tool a little more useful by adding the ability to delete the files it finds. To do this, you’ll add another action to the tool and a new flag del of type bool, allowing the user to enable file deletion.

Learning how to write code that deletes files is an important aspect of creating tools that work with files and perform system administration tasks, but it comes with the risk that you might accidentally delete files you didn’t intend to delete. Make sure that your code is correct to prevent the accidental deletion of files on your computer. Never run this code as a privileged user, as it could cause loss of data or damage to your operating system’s files.

Let’s add another action function called delFile to the file actions.go. This function receives one argument: the file path to be deleted. It returns a potential error that can occur when deleting the file. In the function’s body, call the Remove function from the os package to delete the file. Return the potential error from os.Remove directly as the return value of your function. If os.Remove fails to delete the file, its error will bubble up, stopping the tool’s execution and showing the error message to the user. Define the function delFile like this:

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.