Curly Braces Within Strings Often Mean Substitution Of Variable

#! /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

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

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)}'

5. links

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

Infrastructure Support Engineer/Technical Writer (Snowplow Analytics) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com