Bash curly braces for superpowers!

Bash curly braces are super powerful. You can use them as in-situ loops for expansion to reduce repetitive commands.

A woman with very curly hair that's covering her face. Her smile shines through.

This post is part of the #WeblogPoMo2024 series, the first year I ever join this, and the first blog post in a given year.

I’ve been getting back to Laravel development lately. I was upgrading my Laravel 10 app to Laravel version 11, and what best way to do that is by starting a completely new and empty L11 project and copying / adjusting all my app code into there. It was tedious, but also showed me just how much code I don’t actually need.

One of the tasks I did have to do though was creating a bunch of files so I can display generic http exceptions in a customized way. The standard 400, 401, 402, 403, 404, etc error pages you see on websites when you run into an issue.

Per the Laravel documentation, these files need to live in the resources/views/errors directory, and all of them should be called <errno>.blade.php. That makes the not found page file become 404.blade.php. I also use partials and extend a minimal.blade.php file. That directory did not exist, and thus the files don’t exist either. I tend to create them with the touch command and then add content in my IDE, but there are a lot of files, I’m lazy, and I don’t want to write a bunch of touch commands and repeat .blade.php every time.

Enter the curly braces in bash! It can be used for a bunch of different things, but in my case I’ll use its array builder functionality:

$ echo {foo,bar}baz
// foobaz barbaz

It will loop over each element separated by a comma within the curly braces, and substitute it into whatever is outside the curly braces. The above is equivalent to this:

$ echo foobaz barbaz

I can use this command to generate .blade.php files with the following filenames: 400, 401, 402, 403, 404, 419, 429, 500, 503, minimal.

$ touch {400,401,402,403,404,419,429,500,503,minimal}.blade.php

I can keep grouping them ultimately arriving at this unhinged command:

$ touch {4{0{0,1,2,3,4},19,29},50{0,3},minimal}.blade.php
$ ls
400.blade.php     402.blade.php     404.blade.php     429.blade.php     503.blade.php
401.blade.php     403.blade.php     419.blade.php     500.blade.php     minimal.blade.php

And now you know.

Here’s some more documentation about bash curly braces.

Photo by Tamas Pap on Unsplash