<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Numan, Syed Muhammad on Medium]]></title>
        <description><![CDATA[Stories by Numan, Syed Muhammad on Medium]]></description>
        <link>https://medium.com/@smnuman?source=rss-d146362cb320------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7TARLlZ0JDz0hnIb.jpeg</url>
            <title>Stories by Numan, Syed Muhammad on Medium</title>
            <link>https://medium.com/@smnuman?source=rss-d146362cb320------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:25:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smnuman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Decontaminated a Poisoned Git-Crypt Repo and Rebuilt My Entire Dotfiles Hierarchy]]></title>
            <link>https://medium.com/@smnuman/how-i-decontaminated-a-poisoned-git-crypt-repo-and-rebuilt-my-entire-dotfiles-hierarchy-0b287ca0e979?source=rss-d146362cb320------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b287ca0e979</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[git-crypt]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[dotfiles]]></category>
            <dc:creator><![CDATA[Numan, Syed Muhammad]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 19:24:29 GMT</pubDate>
            <atom:updated>2026-02-22T06:46:58.479Z</atom:updated>
            <content:encoded><![CDATA[<h4>Originally published on <a href="https://numansyed.com/blog/git-crypt-decontamination-submodule-restructure">numansyed.com</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmJ2wGyieewunzJhNDoJFQ.png" /></figure><blockquote><strong>TL;DR:</strong> My dotfiles repo had git-crypt encrypting its own infrastructure files (.gitattributes, .gitmodules, .gitignore), a phantom submodule pointing at itself, and corrupted .gitignore files across the tree. Every grepo command re-poisoned the repo. I fixed it in three phases: encryption decontamination, submodule restructure, and branch/remote cleanup. Here are the war stories and the lessons.</blockquote><h3>The Discovery</h3><p>It started with a simple grepo command failing. I was trying to initialize a new repository from my dotfiles setup, and git-crypt was throwing errors that made no sense. Encryption problems. Files that should be plaintext were being run through encryption filters. git-crypt status was screaming warnings on every single git infrastructure file.</p><p>Then I looked at the submodule status. My zsh/ directory was registered as a submodule in root ~/.config, pointing to smnuman/config-zsh.git. Sounds reasonable, right? Except the <em>root repo itself</em> was also smnuman/config-zsh.git. A submodule pointing at its own parent. A snake eating its own tail.</p><p>And when I dug into the brew/ directory? No remote. No commits. An empty git repo with a .gitignore that blocked everything. Three submodules sitting in detached HEAD states. The whole hierarchy was a mess.</p><p>For context: my <a href="https://github.com/smnuman/dotconfig">dotfiles</a> live in ~/.config and are managed as a tree of git repositories connected via submodules. I use a set of custom <a href="https://github.com/smnuman/zsh-git-utils">Zsh Git utilities</a> (grepo, gsub, gsync) to create, register, and synchronize them. The system is supposed to make dotfiles management effortless. It had done the opposite.Root Cause Analysis: The Self-Reinforcing Poison Loop</p><p>If you’re not familiar with git-crypt: it&#39;s a tool that transparently encrypts files in a git repository. You specify which files to encrypt via patterns in .gitattributes (using filter=git-crypt diff=git-crypt), and git-crypt handles the rest. The key insight is that .gitattributes tells git how to process files during staging and checkout.</p><p>Now, here’s what happened. Someone (possibly me, in a hurry) added these patterns to the .gitcrypt manifest:</p><pre>.git*<br>.gitignore<br>.gitconfig<br>.gitattributes<br>.gitcrypt<br>.gitmodules<br>.gsubignore</pre><p>The intent was probably to “protect everything.” The result was catastrophic. The gencrypt_setup function reads .gitcrypt and writes corresponding rules to .gitattributes. So now .gitattributes contained:</p><pre>.git* filter=git-crypt diff=git-crypt<br>.gitignore filter=git-crypt diff=git-crypt<br>.gitattributes filter=git-crypt diff=git-crypt<br>.gitmodules filter=git-crypt diff=git-crypt</pre><p>Stop and think about that for a second. .gitattributes is the file that <em>tells git how to handle files</em>. We just told git to encrypt .gitattributes itself. Git needs to read .gitattributes to know what to encrypt, but it can&#39;t read it because it&#39;s encrypted. A perfect circular dependency.</p><p>But here’s the truly insidious part: <strong>it was self-reinforcing</strong>. My grepo utility calls gencrypt_setup unconditionally at line 731. Every time I ran grepo to create a new repository, it would regenerate .gitattributes from the poisoned .gitcrypt manifest, re-injecting the poison. Even if I manually fixed .gitattributes, the next grepo would overwrite it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vqf5Z6Dq8g8Qt4V-DLqRkg.png" /></figure><h3>The Phantom Submodule</h3><p>The second problem was a naming collision. My utility function _grepo_name generates repository names using a parent-child format. For ~/.config, the parent directory is the username folder and the child is config, so it generates config-zsh (since the repo was originally zsh-centric). But for ~/.config/zsh, the parent is config and the child is zsh, which also generates… config-zsh.</p><p>Both the root and zsh/ mapped to the same GitHub repo name. When gsub was run to register zsh/ as a submodule, it pointed at the root&#39;s own remote URL. Git dutifully recorded this in .gitmodules. The result: a submodule entry that refers to itself. git submodule status showed -07bf731… with the minus prefix meaning “not initialized” — because git can&#39;t initialize a submodule that points at its own repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpzZpd8-FUZ_U4mSp713GQ.png" /></figure><h3>The .gitignore Corruption</h3><p>A third problem was lurking in the _gisolate function. This helper is meant to prevent parent-child git contamination by writing a .gitignore that blocks everything:</p><pre>*<br>!.gitignore</pre><p>This is fine for a freshly created repo. But when run on a repo that <em>already has</em> a proper .gitignore with carefully curated rules? It overwrites the whole thing. My brew/ and zsh/ directories both had this corruption.</p><h3>Phase A: Encryption Decontamination</h3><p>The fix had to be surgical. I couldn’t just blow away .gitattributes because there were legitimate encryption rules that needed to stay (my .gitconfig has credentials, nomad/* has sensitive project data).</p><p>First, I cleaned the root .gitcrypt manifest, removing all 6 poisoned patterns:</p><pre># Before (poisoned):<br>.git*<br>.gitignore<br>.gitconfig<br>.gitattributes<br>.gitcrypt<br>.gitmodules<br>.gsubignore<br>nomad/*</pre><pre># After (clean):<br>.gitconfig<br>nomad/*</pre><p>Then I cleaned .gitattributes, removing the 7 corresponding encryption rules while keeping the legitimate ones. Same operation on zsh/.gitattributes — removed the .git* patterns, kept docs/*, git_users.zsh, and secrets.key.</p><p>Finally, I ran git-crypt status -f to force-fix the encryption state. This re-staged .gitconfig through the encryption filter. There was one gotcha: git-crypt status -f internally runs git add without the -f flag, so it silently skipped gitignored files like nomad/. I had to manually git add -f nomad/ to fix those.</p><p>Result: zero warnings. All infrastructure files plaintext. All sensitive files properly encrypted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*On7o3avPJ6pmbA3qGoIiNQ.jpeg" /></figure><h3>Phase B: Submodule Restructure</h3><p>With encryption cleaned up, I needed to untangle the phantom submodule. This required careful ordering — git is finicky about submodule operations.</p><pre># 1. Remove phantom entry from .gitmodules<br>#    (edit file to remove [submodule &quot;zsh&quot;] section)<br><br># 2. Clean git config<br>git config --remove-section submodule.zsh<br><br># 3. Remove cached modules directory<br>rm -rf .git/modules/zsh<br><br># 4. Stage .gitmodules first, THEN remove index entry<br>git add .gitmodules<br>git rm --cached zsh</pre><p>That last step is important: git rm --cached zsh refuses to run unless .gitmodules is already staged. Order matters.</p><p>Next, I renamed the root remote from config-zsh to dotconfig, freeing the config-zsh name for zsh/ to use properly:</p><pre>git remote set-url origin git@github.com:smnuman/dotconfig.git</pre><p>Then I initialized zsh/ as its own independent git repository:</p><pre>cd ~/.config/zsh<br>git init<br>git branch -M main<br>git remote add origin git@github.com:smnuman/config-zsh.git<br>git fetch origin<br>git reset --hard origin/main</pre><p>The reset --hard origin/main restored the proper .gitignore (which had been corrupted by _gisolate), the correct .gitmodules, and all tracked files from the remote history.</p><p>After setting up git-crypt and initializing sub-submodules (git-utils and prompt), I registered zsh/ as a proper submodule in root and pushed everything. This required temporarily disabling GitHub branch protection on dotconfig since it enforces PRs even for admins:</p><pre># Disable protection<br>gh api -X DELETE repos/smnuman/dotconfig/branches/main/protection<br><br># Push<br>git push -u origin main --force<br><br># Re-enable protection<br>gh api -X PUT repos/smnuman/dotconfig/branches/main/protection \<br>  --input &lt;(echo &#39;{&quot;required_pull_request_reviews&quot;:{&quot;required_approving_review_count&quot;:1},&quot;enforce_admins&quot;:true,&quot;required_status_checks&quot;:null,&quot;restrictions&quot;:null}&#39;)</pre><h3>Phase C: Branch and Remote Cleanup</h3><p>With the structure fixed, I still had three submodules in bad states.</p><p><strong>zsh/git-utils</strong> was in detached HEAD at commit 038ed81, but had significant uncommitted local work — a new GIT_UTILS_DEBUG toggle, a git-toggle-remote function for switching between GitHub and GitLab, and a git-aliases pretty-printer. The main branch was at 159bb1c (ahead with a .gitignore update). Fix: stash, checkout main, pop stash, commit, push.</p><p><strong>zsh/prompt</strong> was detached at cfe95ac. The main branch was significantly ahead at 6f4a2fe with a cumulative update that subsumed all the orphaned commits. Fix: just git checkout main.</p><p><strong>brew/</strong> was the worst — a git repo with no remote, no commits, and a corrupted .gitignore. But it had plenty of local content (an up-to-date Brewfile, utilities, README) and the remote config-brew existed on GitHub with 21 commits of history. Fix: add remote, fetch, git reset origin/main to graft onto remote history, fix the .gitignore corruption, commit the updated content, push.</p><p>After fixing all three, I propagated submodule pointers bottom-up: zsh/ committed its updated git-utils and prompt pointers, then root committed its updated brew and zsh pointers. Each push to dotconfig required the branch-protection dance.</p><h3>The Final State</h3><pre>~/.config/                    -&gt; smnuman/dotconfig.git<br>  brew/                       -&gt; smnuman/config-brew.git       [submodule]<br>  zsh/                        -&gt; smnuman/config-zsh.git        [submodule]<br>    git-utils/                -&gt; smnuman/zsh-git-utils.git     [submodule]<br>    prompt/                   -&gt; smnuman/zsh-prompt.git        [submodule]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ik8Rvw2JTxzpdqOVVVODQg.png" /></figure><p>All 5 repositories on main, tracking origin/main, fully synced. Zero detached HEADs. Zero missing remotes. Zero uncommitted changes.Lessons Learned</p><p>Seven hard-won takeaways from a long day of git archaeology:</p><ol><li><strong>Never encrypt git infrastructure files.</strong> Files like .gitattributes, .gitmodules, and .gitignore must be plaintext. Encrypting .gitattributes (which controls encryption rules) creates a circular dependency. Encrypting .gitmodules means git can&#39;t discover submodules. Just don&#39;t do it.</li><li><strong>Auto-generated repo names can collide.</strong> If your naming convention is parent-child, make sure a parent and its child can&#39;t resolve to the same name. In my case, both ~/.config and ~/.config/zsh generated config-zsh. Validate uniqueness before pushing.</li><li><strong>Guard your .gitignore from helper functions.</strong> Any utility that writes a .gitignore (like my _gisolate) should check whether one already exists first. Overwriting a curated ignore file with * / !.gitignore silently breaks the entire repo&#39;s file tracking.</li><li><strong>Submodule update always detaches HEAD.</strong> This is by design — git submodule update checks out the exact commit recorded in the parent, not a branch. Always follow it with git checkout main in each submodule if you need to be on a branch.</li><li><strong>Pre-commit hooks produce false positives on .gitattributes.</strong> If your secret-scanning hook greps for patterns like password, secret, or token, it will flag .gitattributes because those words appear in encryption pattern names. Exclude .gitattributes from secret scanning.</li><li><strong>Know how to bypass branch protection in emergencies.</strong> GitHub’s enforce_admins: true blocks even repo owners from direct pushes. For emergency structural fixes: gh api -X DELETE to disable, push, gh api -X PUT to re-enable. Script this if you value your sanity.</li><li><strong>git-crypt status -f doesn’t handle gitignored files.</strong> It runs git add without -f, so gitignored-but-tracked files get silently skipped. Always check for these manually and use git add -f.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SpoZ56X_j4JFM1IQnKG8Dg.png" /></figure><p>The whole operation took most of a day. The repo hierarchy is now clean, every submodule is properly registered and tracked, encryption only touches genuinely sensitive files, and the custom git utilities work without re-poisoning anything. Sometimes you have to tear down the scaffolding to find out the foundation was cracked.</p><p><em>This article was originally published on </em><a href="https://numansyed.com/blog/git-crypt-decontamination-submodule-restructure"><em>numansyed.com</em></a><em>. Cross-posted to Medium with canonical URL pointing to the original. Published under </em><a href="https://policy.medium.com/medium-terms-of-service-9db0094a1e0f"><em>Medium’s Terms of Service</em></a><em> — the author retains all rights to this content. Images: Stock photos from </em><a href="https://unsplash.com/"><em>Unsplash</em></a><em> and </em><a href="https://pexels.com/"><em>Pexels</em></a><em> (free for commercial use). Diagrams by the author.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b287ca0e979" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grep Like a Pro in 2026]]></title>
            <link>https://medium.com/@smnuman/grep-like-a-pro-in-2026-ab69c8a8e42f?source=rss-d146362cb320------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab69c8a8e42f</guid>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[grep]]></category>
            <category><![CDATA[zsh-shell]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Numan, Syed Muhammad]]></dc:creator>
            <pubDate>Sun, 28 Dec 2025 13:38:26 GMT</pubDate>
            <atom:updated>2025-12-28T13:38:26.173Z</atom:updated>
            <content:encoded><![CDATA[<h4>Level Up Your Grep</h4><h4>From Everyday Searches to Color-Coded Mastery</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CjCMgoAX-vNiYCB4" /><figcaption>Photo by <a href="https://unsplash.com/@filisantillan?utm_source=medium&amp;utm_medium=referral">Fili Santillán</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you live in the terminal (zsh, bash, fish, macOS, Linux servers, WSL…), grep is probably in your muscle memory right next to cd .. and git status.</p><p>But most people still use it like it’s 1995 — plain text output, default red highlights (<em>Yak!! I just hate it!!</em>), and endless scrolling through noise.</p><p>In 2026 you can (and should) do better.</p><p>This guide collects the patterns I actually use daily — from quick log greps to beautifully readable coloured output, safe scripting aliases, and tiny tricks that save hours over months.</p><h3>1. The Non-Negotiable Basics (skip if bored)</h3><pre># Case insensitive<br>grep -i &quot;error&quot; app.log<br><br># Show line numbers + filename<br>grep -inH &quot;exception&quot; *.py<br><br># Only filenames that match<br>grep -l &quot;TODO&quot; **/*.js<br><br># Show context (very useful in logs)<br>grep -C 3 &quot;panic&quot; service.log<br># or just after / before<br>grep -A 5 &quot;starting server&quot; startup.log<br>grep -B 2 &quot;shutdown&quot; shutdown.log</pre><h3>2. Invert Match — My Most Used Flag</h3><pre># Show everything *except* debug lines<br>grep -v &quot;DEBUG&quot; app.log | less<br><br># Config files without comments<br>grep -v &quot;^#&quot; nginx.conf</pre><h3>3. Recursive Search — The Real Power Move</h3><pre># Search whole project (skip .git, node_modules, etc.)<br>grep -rI &quot;api_key&quot; .<br><br># Modern alternative — much faster &amp; cleaner<br>rg &quot;api_key&quot;          # ripgrep — install once, never look back<br><br># Only in certain files<br>grep -r --include=&quot;*.{ts,tsx}&quot; &quot;useEffect&quot; src/</pre><h3>4. Make Matches Actually Readable — Custom Colors (2026 Edition)</h3><p>Default red-on-black is okay… until you stare at logs for hours.</p><p>Use GREP_COLORS to tune highlights exactly to your theme.</p><p>Add to ~/.zshrc (or ~/.bashrc):</p><pre># Bold orange matches - very readable on dark backgrounds<br>export GREP_COLORS=&#39;mt=01;38;5;208&#39;<br><br># Or softer purple<br>export GREP_COLORS=&#39;mt=01;38;5;141&#39;<br><br># Match + filename gray + line number green<br>export GREP_COLORS=&#39;mt=01;38;5;208:fn=38;5;244:ln=38;5;108&#39;</pre><p>Reload shell → source ~/.zshrc</p><p>Now every grep --color=auto (or just grep) looks crisp.</p><p>Quick one-liner test:</p><pre>GREP_COLORS=’mt=01;96&#39; grep --color=auto “error” /var/log/*.log</pre><h3>5. Script-Safe Grep — Never Let Colors Break Your Pipes</h3><p>Coloured output kills scripts. Always use a safe alias:</p><pre># In ~/.zshrc<br>alias sgrep=&#39;grep --color=never&#39;<br>alias grep=&#39;grep --color=auto&#39; # interactive = colors, pipe/capture = clean</pre><p>Or smarter (colour only when output is terminal):</p><pre>grep() {<br>  if [[ -t 1 ]]; then<br>      command grep --color=auto &quot;$@&quot;<br>  else<br>      command grep --color=never &quot;$@&quot;<br>  fi<br>}</pre><h3>6. My Daily Aliases / Functions (steal these)</h3><pre># Quick context around errors<br>alias err=&#39;grep -i -C 5 -e error -e warn -e fail -e exception&#39;<br><br># Show IPs in logs (simple regex)<br>alias ips=&quot;grep -oE &#39;\b([0–9]{1,3}\.){3}[0–9]{1,3}\b&#39;&quot;<br><br># Count occurrences<br>alias grepc=&quot;grep -c&quot;<br><br># Only the matching part (very useful - but I had to stop using it, because I have another &#39;grepo&#39; definition)<br>alias grepo=&quot;grep -o&quot;</pre><h3>7. The 2026 Upgrade Path — ripgrep (rg)</h3><p>If you haven’t yet:</p><pre># macOS<br>brew install ripgrep<br><br># Ubuntu/Debian<br>sudo apt install ripgrep<br><br># Arch<br>sudo pacman -S ripgrep</pre><p>Then alias grep → rg in your shell — same flags, 5–10× faster, smart defaults.</p><pre>alias grep=&#39;rg - color=auto&#39;</pre><h3>Closing Thoughts</h3><p>grep is 50+ years old and still unbeatable for 0.1-second feedback loops.</p><p>But small tweaks — colours tuned to your eyes, safe scripting habits, context flags, ripgrep — turn it from “tool” into “superpower”.</p><p>Pick **one** thing from this list today (I vote for custom GREP_COLORS + sgrep alias) and feel the difference tomorrow.</p><p>Happy grepping.</p><p>May your logs always be readable and your false positives few.</p><p>What’s your favourite grep flag / alias? Drop it in the comments — I might steal it too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab69c8a8e42f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zsh’s Hidden Superpower: The ‘always’ Block]]></title>
            <link>https://medium.com/@smnuman/zshs-hidden-superpower-the-always-block-60b7123ed79c?source=rss-d146362cb320------2</link>
            <guid isPermaLink="false">https://medium.com/p/60b7123ed79c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[zsh]]></category>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[zsh-shell]]></category>
            <category><![CDATA[shell-script]]></category>
            <dc:creator><![CDATA[Numan, Syed Muhammad]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 12:22:35 GMT</pubDate>
            <atom:updated>2025-12-22T12:22:35.105Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Why Every Shell Scripter Should Know This Exception-Safe Trick</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iyiPAABF_hTF11Nib7PARQ.png" /><figcaption>The ‘always’ by the auther</figcaption></figure><p>When most people think of shell scripting, they imagine brittle strings of commands held together with hope, tape, and StackOverflow. It works — until it doesn’t. A failed command here, a premature return there, and suddenly your script exits without cleaning up file handles, restoring variables, removing temporary directories, or resetting a program state.</p><p>In Bash, this is simply “how things are”.<br>In Zsh, things are different.</p><p>There is a feature that quietly solves one of scripting’s oldest problems: ensuring clean-up code runs <em>no matter what happens</em>. It’s called the <strong>always</strong> block — and almost nobody talks about it.</p><h3>What is &#39;always&#39;?</h3><p>always is a <em>Zsh-only construct</em> that guarantees a block of code will run after another block finishes — even if the first block:</p><ul><li>returns early</li><li>exits with a non-zero status</li><li>errors out</li><li>is interrupted</li><li>throws an exception via set -e</li><li>contains return, break, or continue</li></ul><p>The syntax looks like this:</p><pre>{<br>    # protected block<br>} always {<br>    # guaranteed block<br>}</pre><p>If you come from Python, think:</p><pre>try:<br>    ...<br>finally:<br>    ...</pre><p>If you come from C++, think RAII destructors.<br>If you come from Bash, think “magic that Bash wishes it had”.</p><h3>Why does it matter?</h3><p>Because real scripts fail in real ways.<br>What happens if:</p><ul><li>a network connection drops?</li><li>a user hits Ctrl-C mid-execution?</li><li>a temporary folder is created but never deleted?</li><li>a variable is overwritten and never restored?</li></ul><p>Enter always.</p><h3>Basic Example</h3><pre>{<br>    print &quot;inside block&quot;<br>    return<br>    print &quot;this will never run&quot;<br>} always {<br>    print &quot;cleanup runs anyway&quot;<br>}</pre><p>Output:</p><pre>inside block<br>cleanup runs anyway</pre><p>Even though the first block returned early, the cleanup ran — automatically.</p><h3>Using &#39;always&#39; inside Functions</h3><pre>backup() {<br>    {<br>        print &quot;Backing up...&quot;<br>        cp important.txt backup.txt<br>        return 0<br>    } always {<br>        print &quot;Backup complete — status recorded&quot;<br>    }<br>}</pre><p>Call:</p><pre>backup</pre><p>No matter what happens during the copy, the backup status message always shows.</p><h3>Example: Temporary Directory Cleanup</h3><p>This is where always shines:</p><pre>process_data() {<br>    {<br>        mkdir /tmp/work<br>        cd /tmp/work<br>        # heavy processing...<br>        return 1         # pretend it fails<br>    } always {<br>        cd /<br>        rm -rf /tmp/work<br>        print &quot;Cleaned temporary directory&quot;<br>    }<br>}</pre><p>Run it:</p><pre>process_data</pre><p>Output:</p><pre>Cleaned temporary directory</pre><p>The folder is removed even on failure.</p><p>Without always, this is a ticking time bomb.</p><h3>Example: Variable State Protection</h3><pre>process() {<br>    {<br>        local old_path=&quot;$PATH&quot;<br>        PATH=&quot;/custom/bin:$PATH&quot;<br>        run_app<br>        return 0<br>    } always {<br>        PATH=&quot;$old_path&quot;<br>        print &quot;PATH restored&quot;<br>    }<br>}</pre><p>Whatever happens:<br> ✔ PATH is guaranteed to be restored.</p><h3>Example: File Descriptor Safety</h3><pre>log_to_file() {<br>    {<br>        exec {FD}&gt;debug.log<br>        print &quot;hello&quot; &gt;&amp;$FD<br>        return 0<br>    } always {<br>        exec {FD}&gt;&amp;-<br>        print &quot;log closed&quot;<br>    }<br>}</pre><p>Never leak file descriptors again.</p><h3>Example: Signal Handling</h3><pre>{<br>    trap &#39;print interrupted&#39; INT<br>    sleep 10<br>} always {<br>    trap - INT<br>    print &quot;signal handler restored&quot;<br>}</pre><p>Even if the user presses Ctrl-C, cleanup happens.</p><h3>Example: Safe Prompt Construction</h3><p>Zsh prompts are notoriously complex. So when temporarily modifying variables in a prompt-rendering function, an always block prevents accidental state corruption:</p><pre>render_prompt() {<br>    {<br>        local old=&quot;$ZSH_DEBUG&quot;<br>        ZSH_DEBUG=1<br>        build_segments<br>    } always {<br>        ZSH_DEBUG=&quot;$old&quot;<br>    }<br>}</pre><h3>Example: Download + Extract</h3><pre>download_file() {<br>    {<br>        wget &quot;$1&quot; -O /tmp/file.tar.gz<br>        tar -xf /tmp/file.tar.gz -C /tmp<br>        return 0<br>    } always {<br>        rm -f /tmp/file.tar.gz<br>        print &quot;Download cleaned&quot;<br>    }<br>}</pre><p>Even if the download fails halfway — temporary files don’t linger.</p><h3>Example: Loop Cleanup</h3><p>Yes — the always construct even works in loops:</p><pre>while get_more_items; do<br>    {<br>        do_step<br>        continue<br>    } always {<br>        print &quot;step done&quot;<br>    }<br>done</pre><p>continue does not skip the cleanup.</p><h3>Common Misuse</h3><p>You can’t attach an always block directly to a function’s closing brace:</p><p>❌ Invalid:</p><pre>fn() {<br>    ...<br>} always {<br>    ...<br>}</pre><p>✔ Correct:</p><pre>fn() {<br>    {<br>        ...<br>    } always {<br>        ...<br>    }<br>}</pre><p>Keep always glued to a { ... } block, not a function body.</p><h3>Performance Impact</h3><p>Minimal.<br>Zsh does not wrap the entire interpreter — it simply manages block execution order.</p><p>In other words:<br> always is virtually free.</p><h3>Portability Warning</h3><p>This feature is <strong>Zsh-only</strong>.</p><p>If you write scripts that must run in:</p><ul><li>bash</li><li>dash</li><li>ash</li><li>ksh</li><li>sh</li></ul><p>…avoid using it.</p><p>But for systems where Zsh is the default, you’ve been given a luxury.</p><h3>Why always is Special</h3><p>Because it protects logic the same way exception handling protects code in higher-level languages.</p><p>It removes fear.<br>It removes uncertainty.<br>It removes fragile edges.</p><p>And it turns messy shell scripts into robust, professional-grade tooling.</p><h3>Final Thoughts</h3><p>Zsh’s always construct is one of the language’s most underrated features. It allows shell scripts to behave like mature programs — resilient, predictable, and recoverable.</p><p>Once you begin using it for:</p><ul><li>cleanup</li><li>resource management</li><li>environment control</li><li>reversible operations</li><li>exception safety</li></ul><p>…you will wonder how you ever scripted without it.</p><p>The power is there for the taking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60b7123ed79c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>