Refactoring

2025-04-22

---

Since 2019, I've maintained a shell script that creates and manages a microjournaling file. I made it entirely for personal use, mimicking an esoteric use case for Twitter, and while I've shared the script on my capsule, I'm pretty sure nobody uses it except me.^

I first posted the script to Gemini on 2021-11-03. At that time, it was minimally-developed and the code was very unpolished. It was also heavily tailored to my particular use case. 3 1/2 years and almost 100 releases later, I've greatly expanded the script's capabilities--it can now do everything from parsing command-line options to generating avatar files, to cross-posting to twtxt files, to merging divergent timeline files, and more. I daresay I'm pretty proud of what I built.

Over the course of developing the program, I've learned a lot about shell scripting, and I've learned even more about POSIX. The initial version included several Bash-isms that I didn't know how to work around, because I wasn't familiar enough with the various tools available to me. A major goal of the project was to enforce full POSIX compliance by v1.0, which finally happened almost a year and a half after I first shared it. But even then, I soon discovered that I was only following POSIX in the shell commands themselves; some of the external utilities were still using GNU or BSD extensions. That took some time to figure out.

While the script changelog on my capsule goes back to v0.3.9.1, the oldest version I still have access to it v0.4.3, which is the first version I posted on my capsule. Today I decided it would be a fun exercise to refactor that "base" version with some of the scripting techniques I use now. My goal was to keep identical functionality to v0.4.3 (while fixing at least two bugs I know were present) and reduce the size of the script as much as I could within an hour or so.

The resulting work was quite fun. I managed to reduce about 190 lines of code into about 140, and the overall size of the file shrank from 8503 bytes to 6134 bytes. A large part of the difference came from using hard tabs instead of soft. However, the biggest savings came from converting many 'if' statements into 'case' statements or logical ANDs. Several operations could be swapped out for more compact versions; surprisingly, most of them ended up being more readable or more robust than their more verbose counterparts. I even found one invocation in the original file (grep -oPz) that GNU explicitly warns is experimental!

After my exercise, the refactored v0.4.3 is much cleaner and runs better. I don't have any intention to use it regularly, as it is still completely incompatible with the current version (v5.0.4). But I enjoyed seeing the fruits of my learning by being able to refactor my own work so thoroughly. It helps me feel more confident in my abilities as a script writer.

^ Offline Microblog

---

Up One Level
Home

[Last updated: 2025-04-22]