Introduction to Bash Scripting
Alex Scriven
Data Scientist
Numbers are not built in natively to the shell like most REPLs (console) such as R and Python
In Python or R you may do:
>>> 1 + 4
5
It will return what you want!
Numbers are not natively supported:
(In the terminal)
1 + 4
bash: 1: command not found
expr
is a useful utility program (just like cat
or grep
)
This will now work (in the terminal):
expr 1 + 4
5
Nice stuff!
expr
cannot natively handle decimal places:
(In terminal)
expr 1 + 2.5
expr: not a decimal number: '2.5'
Fear not though! (There is a solution)
bc
(basic calculator) is a useful command-line program.
You can enter it in the terminal and perform calculations:
Using bc
without opening the calculator is possible by piping:
echo "5 + 7.5" | bc
12.5
bc
also has a scale
argument for how many decimal places.
echo "10 / 3" | bc
3
echo "scale=3; 10 / 3" | bc
Note the use of ;
to separate 'lines' in terminal
3.333
We can assign numeric variables just like string variables:
dog_name='Roger' dog_age=6
echo "My dog's name is $dog_name and he is $dog_age years old"
Beware that dog_age="6"
will work, but makes it a string!
My dog's name is Roger and he is 6 years old
A variant on single bracket variable notation for numeric variables:
expr 5 + 7
echo $((5 + 7))
12
12
Beware this method uses expr
, not bc
(no decimals!)
Remember how we called out to the shell in the previous lesson?
Very useful for numeric variables:
model1=87.65 model2=89.20
echo "The total score is $(echo "$model1 + $model2" | bc)"
echo "The average score is $(echo "($model1 + $model2) / 2" | bc)"
The total score is 176.85
The average score is 88
Introduction to Bash Scripting