Introduction to Bash Scripting
Alex Scriven
Data Scientist
A Bash script has a few key defining features:
#!/usr/bash
(on its own line)/usr/bash
/bin/bash
(type which bash
to check)To save and run:
.sh
#!/usr/bash
), but a conventionbash script_name.sh
#!/usr/bash
) you can simply run using ./script_name.sh
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
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.
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