Curly Braces Within Strings Often Mean Substitution Of Variable
The aim of this pageđź“ťis to describe variable interpolation from strings in bash. For example you want to use a variable $topic
in the script. If the symbol is combined with a literal value it is problematic to see which is which in e.g. echo $date: $note >> ~/$topicnotes.txt
.
For this use, languages I use typically employ curly braces {<symbol>}
— this is also in many other instances like SQL, I see that in config files and HTML templating.
#! /bin/bash
date=$(date)
topic=$1
read -p "Your note:" note
echo $date: $note >> ~/$topicnotes.txt #see `$topic` variable is not separated from 'notes.txt' literal
echo Note saved: $note
Bash is old — note that posh, js and python come only in 2000s or late 2010s with the support for this.
1. Bash
- the example from the intro is fixed to become
#! /bin/bash
date=$(date)
topic=$1
read -p "Your note:" note
echo $date: $note >> ~/${topic}notes.txt #see `$topic` variable is not separated from 'notes.txt' literal
echo Note saved: $note
2. Powershell
$foo = 'bar' # example variable
# INCORRECT: PowerShell assumes that the variable name is 'foobarian', not 'foo'
PS> "A $foobarian."
>>>A . # Variable $foobarian doesn't exist -> reference expanded to empty string.
# CORRECT: Use {...} to delineate the variable name:
PS> "A ${foo}barian."
>>>A barbarian.
# INCORRECT: PowerShell assumes that 'foo:' is a *namespace* (drive) reference
# (such as 'env:' in $env:PATH) and FAILS:
PS> "$foo: bar"
>>> Variable reference is not valid. ':' was not followed by a valid variable name character.
# Consider using ${} to delimit the name.
# CORRECT: Use {...} to delineate the variable name:
PS> "${foo}: bar"
bar: bar
— from https://stackoverflow.com/a/60329476/11082684
3. JavaScript
- in JS you need another step — to enclose this in backticks to create so called template literals
- ths was introduced in ES2015
let a = 5;
let b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."
4. Python
- also in 2015, python introduced f strings — formatted strings with Python 3.6
>>> f'Column={col_idx+1}'
>>> f'number of items: {len(items)}'
— from https://www.python.org/dev/peps/pep-0498/#supporting-full-python-expressions