How can I simplify my bash script for finding and editing empty directories?

0
13
Asked By CodingWhale42 On

I've created a simple bash script that recursively finds empty directories and opens them in vim for the user to edit. The user can delete lines from the list to exclude certain directories from being removed. After saving and exiting vim, the script prompts for the final confirmation on which directories to delete. I'm looking for ways to simplify or improve the script, and I'm open to all kinds of constructive feedback, no matter how minor it may seem. Also, I prefer using bash features since I'm already employing arrays. Any advice from seasoned bash users would be greatly appreciated!

4 Answers

Answered By ScriptSavvy On

Start by clarifying your program's logic. Decide if you’re only targeting completely empty directories, or if directories with only directory descendants should be included too. This will impact how user interactions are structured. Think about how you want to prompt users—is it all at once, or step by step as you encounter directories? Getting this functionality planned out will help you code it more effectively. Also, ensure you handle all pathname types properly, since files can technically have pretty wild characters in their names.

Answered By TechGuru99 On

You could streamline your script by redirecting the directory list directly to a file rather than collecting files into an array first. Also, be cautious with how you're handling special characters in filenames, as that might break the format of your temp file. It's best to simplify those printf statements, too, as they seem overly complex. Consider rethinking the usage of `awk` since it could fail on unique directory names. Lastly, be sure you're calling `rmdir` correctly by checking the order in your arrays.

Answered By QueryMaster On

Just a heads up that `find` isn't a bash-ism—it's part of core utilities, so it's safe to use. I'm glad to see you're utilizing `printf` as well. If you want, you can simplify your checks for empty directories by using a simple arithmetic evaluation instead of an if statement. Just be cautious with default command names like `fd`, as they might conflict with other commands. Overall, it sounds like your script is meant for interactive use—a good approach!

Answered By DevNinja88 On

A few quick tips: You can initialize your dirs array using `dirs=("${@:-.}")`, which avoids the need for an `if` check. Instead of using an `else` after checking for empty directories, just exit if you find none and keep your logic straightforward. Also, make sure to run `shellcheck` to find any variables in your script that aren't defined—this can save you a lot of debugging time!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.