Introduction to Bash Scripting
Alex Scriven
Data Scientist
Similar to other languages, you can assign variables with the equals notation.
var1="Moon"
Then reference with $
notation.
echo $var1
Moon
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!
If you miss the $
notation - it isn't a variable!
firstname='Cynthia'
lastname='Liu'
echo "Hi there " firstname lastname
Hi there firstname lastname
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
In Bash, using different quotation marks can mean different things. Both when creating variables and printing.
'sometext'
) = Shell interprets what is between literally"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.
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
The Date
program will be useful for demonstrating backticks
Normal output of this program:
date
Mon 2 Dec 2019 14:07:10 AEDT
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!
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