BASH 101 Tutorial

Bash, short for Bourne-Again SHell, is a command-line interface (CLI) for Unix-based operating systems. It is a powerful tool for anyone who works in a command-line environment. In this 101 tutorial, we will cover the basics of Bash to help you get started.

What is Bash

Bash is a command-line interpreter that allows you to interact with your computer using text-based commands without the need for a graphical user interface. Bash was created by Brian Fox. He developed Bash as a free and open-source Unix shell program while working as a programmer at the Free Software Foundation (FSF). Brian Fox released the first version of Bash in June 1989, and it has since become one of the most widely used command-line interfaces on Unix-like operating systems.

How to Open Bash

Before we dive into Bash commands, let’s first learn how to open it. The steps might vary depending on your operating system:

For Linux:

  1. Terminal: Open your Terminal application. You can usually find it in your Applications or System Tools menu.

For macOS:

  1. Terminal: Just like Linux, you can find the Terminal in your Applications folder, or simply search for it using the spotlight search.

For Windows:

  1. Windows Subsystem for Linux (WSL): If you’re using Windows 10 or later, you can install WSL and use a Linux distribution like Ubuntu, which includes Bash.
  2. Git Bash: If you have Git installed, you can open Git Bash, which provides a Bash-like environment.

As mentioned above, Bash commands can perform many of the same functions as an operating system’s graphical user interface. Additionally, Bash provides syntax similar to a programming language so that it allows you to create custom scripts to automate tasks. Let’s explore these features.

Variables

One of the key features of Bash is its support for variables. As in other programming languages, they are used to store values so that values can be accessed and manipulated by Bash commands and scripts.

How To Define Bash Variables

Bash variables can be defined in a number of ways. The simplest way is to assign a value to a variable using the = operator. For example, the following command creates a variable called myvar and sets its value to hello

myvar="hello"

You can also create a variable without assigning a value to it by simply declaring it. For example, the following command creates the same variable without assigning a value

myvar=

How To Get A Variable From User

Another way to define a variable is to use the read command to read input from the user and store it in a variable. For example, the following command prompts the user to enter a value and stores it in the myvar variable:

read -p "Enter a value: " myvar

How To Access Bash Variables

Once you have defined a Bash variable, you can access its value using the $ operator. For example, to print the value of the myvar variable, you can use the echo command as follows:

echo $myvar

You can also use the curly braces {} to enclose the variable name when accessing it. This is useful when you want to concatenate a variable with other text.

For example

echo "The value of myvar is ${myvar}."

Additionally, you might define a variable to store the name of a file and use it for file-related operations such as create, remove and update a file.

touch $filename

Data Types

Bash provides several data types that are used to store different types of information such as numbers, strings, and arrays.

String

Strings are sequences of characters enclosed in single or double quotes. Bash treats single and double quotes differently. Single quotes preserve the literal value of all characters within the quotes, whereas double quotes allow the expansion of variables and some special characters.

For example

string='Hello World'
echo $string        # prints 'Hello World'

string="Hello $USER"
echo $string        # prints 'Hello <username>'

Numbers

Bash supports integers and floating-point numbers. Integers can be represented in decimal, octal, or hexadecimal format. To represent an integer in octal, use a leading zero (0), and to represent a number in hexadecimal format, use a leading ‘0x’. For example:

num1=10             # decimal
num2=012            # octal
num3=0xA            # hexadecimal
echo $num1 $num2 $num3    # prints '10 10 10'

Floating-point numbers are represented using the ‘bc’ utility or the ‘awk’ command. For example:

float=$(echo "scale=2; 3/2" | bc)
echo $float         # prints '1.50'

Arrays

Arrays are variables that can hold multiple values. Bash arrays are zero-indexed, meaning that the first element of an array is at index 0. To declare an array, use parentheses and separate the values with spaces.

For example

arr=(apple banana cherry)
echo ${arr[0]}      # prints 'apple'

To access all the elements of an array, use the ‘@’ or ‘*’ symbol. For example:

echo ${arr[@]}      # prints 'apple banana cherry'
echo ${arr[*]}      # prints 'apple banana cherry'

Associative arrays

Associative arrays are arrays that use keys instead of numerical indices similar to the map data structure in programming languages. To declare an associative array, use the ‘declare -A’ command. For example:

declare -A assoc_arr
assoc_arr["name"]="John"
assoc_arr["age"]=30
echo ${assoc_arr["name"]} is ${assoc_arr["age"]} years old.
# This will output: 'John is 30 years old.'

If Else Conditions

In this step, we will discuss one of the most important constructs in Bash, the if clause, which allows you to make decisions based on the results of tests and conditions.

The if clause in Bash is used to execute a block of code only if a certain condition is true. The basic syntax of the if clause is as follows:

if [ condition1 ]; then
    # code to execute if condition1 is true
elif [ condition2 ]; then
    # code to execute if condition2 is true
else
    # code to execute if both condition1 and condition2 are false
fi

In this syntax, the if keyword is followed by a square bracket [ which is used to enclose the first condition to be tested. The then keyword marks the beginning of the code block to be executed if the first condition is true.

The elif keyword is used to test the second condition, followed by another code block to execute if the second condition is true.

The else keyword is optional and marks the beginning of the code block to execute if both conditions are false. Finally, the fi keyword marks the end of the entire statement.

Example

Let’s look at an example that demonstrates the use of the if clause in Bash:

#!/bin/bash

# Prompt user for a number
echo "Enter a number between 1 and 10: "
read num

# Test the number entered
if [ "$num" -lt 1 ] || [ "$num" -gt 10 ]; then
    echo "Invalid number entered!"
elif [ "$num" -lt 5 ]; then
    echo "Number is less than 5"
else
    echo "Number is greater than or equal to 5"
fi

In this example, we first prompt the user to enter a number between 1 and 10, and store the input in the $num variable. We then use the if statement to test whether the number entered is less than 1 or greater than 10. If so, we print a message indicating that an invalid number was entered. If not, we use the elif statement to test whether the number is less than 5. If it is, we print a message indicating that the number is less than 5. Otherwise, we print a message indicating that the number is greater than or equal to 5.

For Loop

In bash, the for loop allows you to run a block of code repeatedly, once for each value in a list or array. The for loop is a key tool for writing scripts that automate repetitive tasks or process large amounts of data.

The basic syntax for the for loop in bash is as follows:

for variable in list
do
  # code to be executed
done

In this syntax, variable is a user-defined variable that will take on each value in the list of values. The block of code between the do and done keywords will be executed once for each value of variable.

For example, consider the following code:

for i in 1 2 3 4 5
do
  echo $i
done

This code will print the numbers 1 through 5 to the terminal, each on a new line.

In addition to explicitly listing the values in the list, you can also use the for loop to iterate over a range of values using the seq command. The seq command generates a sequence of numbers from a starting value to an ending value, with an optional step size.

Here’s an example:

for i in $(seq 1 2 10)
do
  echo $i
done

This code will print the odd numbers from 1 to 10 to the terminal.

You can also use the for loop to iterate over the elements of an array. To define an array, you can use the declare command, as follows:

declare -a my_array=("apple" "banana" "cherry")

Then, you can use the for loop to iterate over the elements of the array, like this:

for fruit in "${my_array[@]}"
do
  echo $fruit
done

This code will print the elements of the my_array array to the terminal, each on a new line.

BASH File Operations

Bash is mainly used for performing file-related operations. With the commands that bash provide, you can create, remove, copy or move a file in file-sytem without using the graphical user interface.

These basic commands are as follows:

pwd – Print Working Directory

This command tells you which directory (folder) you are currently in. It’s like asking, “Where am I?”

pwd

ls – List Files and Directories

Use this command to list the files and directories in your current location.

ls

cd – Change Directory

You can navigate to different directories using the cd command. For example, to move into a directory called “myfolder,” you would type:

cd myfolder

And to go back to the previous directory:

cd ..

mkdir – Make Directory

Need to create a new directory? The mkdir command will create one

mkdir newfolder

touch – Create Empty Files

Create empty text files with the touch command.

touch myfile.txt

cp – Copy Files or Directories

To copy a file or directory, use the cp command. For instance, to copy “file1.txt” to a new location:

cp file1.txt /path/to/destination/

mv – Move or Rename Files

The mv command is used to move files or rename them. To move a file:

mv file1.txt /path/to/destination/

And to rename a file:

mv oldfile.txt newfile.txt

rm – Remove Files or Directories

To delete a file, use the rm command. Be careful, though; there’s no “undo” button.

rm myfile.txt

To delete a directory and its contents:

rm -r myfolder

cat – View File Content

The cat command lets you view the contents of a text file on the command line.

cat myfile.txt

echo – Print to the Terminal

Use echo to print text to the terminal.

echo "Hello, Bash!"

Conclusion

BASH is a powerful tool for anyone especially developers who works in a command-line environment. It allows you to write scripts to automate some tasks and handle file-related operations with ease without using the graphical interface.

In this 101 tutorial, we’ve talked about bash scripting, which consists of several programming language-like expressions, such as if clauses, for loops, data types, etc. Additionally, we discussed how to use Bash for file operations.

Thank you for reading.

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top