Basic variables in Bash

Introduction to Bash Scripting

Alex Scriven

Data Scientist

Assigning variables

Similar to other languages, you can assign variables with the equals notation.

var1="Moon"

Then reference with $ notation.

echo $var1
Moon
Introduction to Bash Scripting

Assigning string variables

Name your variable as you like (something sensible!):

firstname='Cynthia'
lastname='Liu'

echo "Hi there" $firstname $lastname
Hi there Cynthia Liu

Both variables were returned - nice!

Introduction to Bash Scripting

Missing the $ notation

If you miss the $ notation - it isn't a variable!

firstname='Cynthia'
lastname='Liu'
echo "Hi there " firstname lastname
Hi there firstname lastname
Introduction to Bash Scripting

(Not) assigning variables

Bash is not very forgiving about spaces in variable creation. Beware of adding spaces!

var1 = "Moon"
echo $var1
script.sh: line 3: var1: command not found
Introduction to Bash Scripting

Single, double, backticks

In Bash, using different quotation marks can mean different things. Both when creating variables and printing.

  • Single quotes ('sometext') = Shell interprets what is between literally
  • Double quotes ("sometext") = Shell interprets literally except using $ and backticks

The last way creates a 'shell-within-a-shell', outlined below. Useful for calling command-line programs. This is done with backticks.

  • Backticks (`sometext`) = Shell runs the command and captures STDOUT back into a variable
Introduction to Bash Scripting

Different variable creation

Let's see the effect of different types of variable creation

now_var='NOW'

now_var_singlequote='$now_var' echo $now_var_singlequote
$now_var
now_var_doublequote="$now_var"
echo $now_var_doublequote
NOW
Introduction to Bash Scripting

The date program

The Date program will be useful for demonstrating backticks

Normal output of this program:

date
Mon  2 Dec 2019 14:07:10 AEDT
Introduction to Bash Scripting

Shell within a shell

Let's use the shell-within-a-shell now:

rightnow_doublequote="The date is `date`."
echo $rightnow_doublequote
The date is Mon 2 Dec 2019 14:13:35 AEDT.

The date program was called, output captured and combined in-line with the echo call.

We used a shell within a shell!

Introduction to Bash Scripting

Parentheses vs backticks

There is an equivalent to backtick notation:

rightnow_doublequote="The date is `date`."
rightnow_parentheses="The date is $(date)."
echo $rightnow_doublequote
echo $rightnow_parentheses
The date is Mon 2 Dec 2019 14:54:34 AEDT.
The date is Mon 2 Dec 2019 14:54:34 AEDT.

Both work the same though using backticks is older. Parentheses is used more in modern applications. (See http://mywiki.wooledge.org/BashFAQ/082)

Introduction to Bash Scripting

Let's practice!

Introduction to Bash Scripting

Preparing Video For Download...