Neko

Bash Basics

An intro to bash that only covers the essentials to get you started.


Last updated: May 4th, 2023

One-Liners

Bash one-liners are lines of code that can be executed on a single line in a bash terminal. They typically use loops, pipes, output redirections and many other useful methods for automating repetitive tasks in the shell. While writing this, I found a super useful series that can be used as a reference when creating bash one-liners called: "Next up – Bash One-Liners" near the bottom of the page. I highly recommend reading each post in the bash section thoroughly as much of what is talked about I use or come across daily.

Shell Scripts

Shebang

Bash files will start with a shebang. You can read about them here: Shebang_(Unix)

Variables

In bash there are local variables, which are only available within the block of code where they are defined and global variables, which we will cover below and are also called environment variables.

Here is an example defining and calling a local variable

#!/bin/bash
exampleVar="Hello"
echo $exampleVar

Environment Variables

An environment is an array of strings that are passed to a program when the program is executed. Environment variables are the key-value pairs that make up that array and provide information about the system.

You can check the current env vars with:

printenv
Running commands with sudo will change, add and remove some vars while in the elevated environment, this can be observed by running:
sudo printenv
Keep this in mind when making scripts meant to run with sudo.

Setting environment variables can be done with:

export <KEY>=<VALUE>

Bash has positional variables. $0 is the name of the program. $n are the arguments where n is a number >= 1. These arguments are defined when the program is executed on the commandline and can then be called in a script.

/usr/bin/cat program.sh
#!/bin/bash
printf "The program you are running is $0 \n $3 $1$2"
./program.sh  world ! Hello

The program you are running is /home/erodgers/Desktop/eli2k/program.sh
Hello world!⏎

Bash has a few special variables. This post talks about them and gives examples: Bash Special Parameters Explained with 4 Example Shell Scripts

Bash has prompt variables. This post elaborates and gives some examples: How To Make A Custom Bash Shell Prompt.

If/Then

This post goes in-depth about conditionals in bash: How To Script Error Free Bash If Statements?

To test what you learned I recommend attempting the Onboarding Challenge, Power of Thor Challenge, and Mars Lander Challenge at CodingGame. The site visualises the code you write in the form of games and allows you to choose from several languages. It also allows you to skip the account creation. We will be using that site in the future so you may want to create an account.

Loops

Read through the following post and answer the questions below:

What is the Right Way to do Bash Loops?

Questions:

  • How do you iterate over a list of files? How about lines in a file?
  • What are the four types of iteration constructs? Describe how each of those can be implemented in bash, feel free to make scripts for each.
  • What are the break keyword and continue keywords used for?
  • How would you perform a do-while loop in bash?

This challenge is optional if you were able to answer and implement the questions above. It is quite fun and will prepare you for the next challenge so I do recommend doing it: The Descent

Arrays

Another informative post by Shell-Tips about arrays is below.

A Complete Guide on How To Use Bash Arrays

Attempt to answer these questions after reading that post:

  • What are the two types of arrays in bash and how are they declared?
  • How do you reference an item stored in an array?
  • How do you remove a key from an array?
  • How do you loop over an array?

Now that you're familiar with loops and arrays do these challenges:

  1. Temperatures
  2. Ascii-art
  3. Rock-Paper-Scissors

Functions

For our last topic in bash you will be learning about functions. I won't be providing any problems for this one, but I do suggest you challenge yourself in a way you see fit. The recommended reading is here: The Complete How To Guide of Bash Functions

There is a lot more to bash than what I showed here but hopefully this will get you started.

Summary

#Variables
exampleVar="Hello"
echo $exampleVar

#If/then
if $some_var > 10; then
    echo "some_var is totally bigger than 10."
elif some_var < 10; then    # This elif clause is optional.
    echo "some_var is smaller than 10."
else:                  # This is optional too.
    echo "some_var is indeed 10."

#For Loops
for number in {0..4..1}; do
  echo " ${number}"
done

for ((x=0 ; x<5 ; x++)); do
  echo "$x"
done

#While Loops
x = 0
while (( x < 4 )); do
    echo $((x++))
done

#Arrays (lists)
myIndexedArray=(one two three)
echo ${myIndexedArray[*]}

for value in "${myIndexedArray[*]}"; do echo "$value"; done

#Functions
fn() { echo "Hello World!"; }

#Calling Functions
fn      # => Hello World!