Your first Bash script

Introduction to Bash Scripting

Alex Scriven

Data Scientist

Bash script anatomy

A Bash script has a few key defining features:

  • It usually begins with #!/usr/bash (on its own line)
    • So your interpreter knows it is a Bash script and to use Bash located in /usr/bash
    • This could be a different path if you installed Bash somewhere else such as /bin/bash (type which bash to check)
  • Middle lines contain code
    • This may be line-by-line commands or programming constructs
Introduction to Bash Scripting

Bash script anatomy

To save and run:

  • It has a file extension .sh
    • Technically not needed if first line has the she-bang and path to Bash (#!/usr/bash), but a convention
  • Can be run in the terminal using bash script_name.sh
    • Or if you have mentioned first line (#!/usr/bash) you can simply run using ./script_name.sh
Introduction to Bash Scripting

Bash script example

An example of a full script (called eg.sh) is:

#!/usr/bash
echo "Hello world"
echo "Goodbye world"

Could be run with the command ./eg.sh and would output:

Hello world
Goodbye world
Introduction to Bash Scripting

Bash and shell commands

Each line of your Bash script can be a shell command.

Therefore, you can also include pipes in your Bash scripts.

Consider a text file (animals.txt)

magpie, bird
emu, bird
kangaroo, marsupial
wallaby, marsupial
shark, fish

We want to count animals in each group.

Introduction to Bash Scripting

Bash and shell commands

In shell you could write a chained command in the terminal. Let's instead put that into a script (group.sh):

#!/usr/bash
cat animals.txt | cut -d " " -f 2 | sort | uniq -c

Now (after saving the script) running bash group.sh causes:

   2 bird
   1 fish
   2 marsupial
Introduction to Bash Scripting

Let's practice!

Introduction to Bash Scripting

Preparing Video For Download...