Introduction and Refresher: Alex Scriven
Introduction and Refresher: Alex Scriven
refresher
I N T R O D U C T I O N TO B A S H S C R I P T I N G
Alex Scriven
Data Scientist
Introduction to the course
This course will cover:
Control statements
Developed in the 80's but a very popular shell today. Default in many Unix systems, Macs
You are expected to have some basic knowledge for this course.
You will often need to lter les, data within les, match arguments and a variety of other uses. It is
worth revisiting this.
To test your regex you can use helpful sites like regex101.com
banana
apple
carrot
banana
apple
carrot
apple
Recall that square parentheses are a matching set such as [eyfv] . Using ^ makes this an inverse set
(not these letters/numbers)
apple
carrot
If we wanted the top n fruits we could then pipe to wc -l and use head
14 apple
13 bannana
12 carrot
Alex Scriven
Data Scientist
Bash script anatomy
A Bash script has a few key de ning features:
This could be a different path if you installed Bash somewhere else such as /bin/bash (type
which bash to check)
#!/usr/bash
echo "Hello world"
echo "Goodbye world"
Hello world
Goodbye world
magpie, bird
emu, bird
kangaroo, marsupial
wallaby, marsupial
shark, fish
#!/usr/bash
cat animals.txt | cut -d " " -f 2 | sort | uniq -c
2 bird
1 fish
2 marsupial
Alex Scriven
Data Scientist
STDIN-STDOUT-STDERR
In Bash scripting, there are three 'streams' for your program:
By default, these streams will come from and write out to the terminal.
Though you may see 2> /dev/null in script calls; redirecting STDERR to be deleted. (
1> /dev/null would be STDOUT)
football
basketball
swimming
The cat sports.txt 1> new_sports.txt command is an example of taking data from the le and
writing STDOUT to a new le. See what happens if you cat new_sports.txt
football
basketball
swimming
Bash scripts can take arguments to be used inside by adding a space after the script execution call.
Each argument can be accessed via the $ notation. The rst as $1 , the second as $2 etc.
#!/usr/bash
echo $1
echo $2
echo $@
echo "There are " $# "arguments"