Why You Should Put Braces around Your Variables When Shell Scripting
Braces are often optional but they're almost always worth using for consistency, reducing confusion and using certain features.
A few years ago I wrote a post about the importance of quoting your variables in Bash and while it touched base on using braces but didn’t go into much detail about them.
This video goes into a few use cases on why I always put braces around my variables. It doesn’t matter if you’re using regular shell, bash, zsh or any other shell interpreter. It’s always worth it.
# Demo Video
Examples
Here’s an example
script to demonstrate a few things:
#!/usr/bin/env bash
person="Nick"
prefix="cus"
id="abc123"
git_sha="6a18ebb566f1becbbc36545d9038a1452b4aec55"
colors=(red blue green)
cat << EOF
${greeting:-Hey} ${person}, here's a few examples:
Is ${person} cool? $personiscool
Is ${person} cool? ${person}iscool
Database ID: $prefix_id
Database ID: ${prefix}_${id}
Short git SHA: $git_sha:0:8
Short git SHA: ${git_sha:0:8}
What color is the sky? $colors[1]
What color is the sky? ${colors[1]}
All args: ${@}
10th arg: $10
10th arg: ${10}
EOF
Running this with ./example a b c d e f g h i j
, produces this output:
Hey Nick, here's a few examples:
Is Nick cool?
Is Nick cool? Nickiscool
Database ID:
Database ID: cus_abc123
Short git SHA: 6a18ebb566f1becbbc36545d9038a1452b4aec55:0:8
Short git SHA: 6a18ebb5
What color is the sky? red[1]
What color is the sky? blue
All args: a b c d e f g h i j
10th arg: a0
10th arg: j
Timestamps
- 0:07 – Quoting your variables is important too
- 0:44 – Taking a look at an example script that demos a few use cases
- 0:54 – Defining a default value
- 1:46 – Help visualize what is part of a variable or a string
- 2:12 – Clearly separating variables when an underscore is involved
- 3:04 – Truncating a variable’s output in Bash
- 3:59 – Reference a specific index in an array
- 4:45 – Being able to reference more than 9 command line arguments
- 5:39 – ShellCheck will call out when you’re not using braces
Reference Links
Do you always use braces when shell scripting? Let me know below.