An Introduction Guide to using Bash

An Introduction Guide to using Bash

·

10 min read

Overview

This article will explain how to use Bash by creating and using the following data types or techniques:

  • Outputting Statements

  • Creating Strings

  • Declaring Variables

  • Integers or Floats

  • Printing Saved Variable Data

  • Clearing the Terminal

  • Navigating through the Terminal

  • Making and Deleting Directories or Folders

  • Making and Deleting Files or Scripts

  • Editing, Executing and Writing Scripts

    • Making Comments

    • Conditionals

      • If, Elif, Else statements

      • Nested If Functions

      • For Loops

      • While Loops

    • Functions

    • Deleting Entire Lines in a Script

Materials

  • Computer

  • Terminal or Program that uses Bash

How to Output Statements

Statements are outputted by using the "echo" command

echo "What words are in the quotations, will be printed the way it appears"

Creating Strings

As shown above, in the first example, a statement enclosed within single quotes '' or double quotes "", is considered a string

# Using echo to Output Statements
echo "Hello. This is another statement."

Declaring Variables

A variable can be declared by assigning a letter or word to a statement

# Creating a Variable
make_a_variable="This is a variable"

Notice, there cannot be any spaces between the variable name, the equal sign, and what data the variable holds

Integers or Floats

Numbers such as integers or floats are another data type that can be declared. Assign a variable to a number for it to contain number data.

# Create a Variable that holds an Integer
a=15

The difference between an integer and a float is, an integer is a whole number such as 0, 1, 2, or 3 .... while floats are decimal numbers such as 0.6, 1.3, 2.2, 3.1. A float can be declared similarly as an integer.

# Create a Variable that holds a Float Value
b=2.7

Printing Saved Variable Data

Variables that are once saved such as "make_a_variable", "a", and "b" can be printed out with echo and placing a "$" before the variable name as shown below:

echo $make_a_variable

echo $a

echo $b

Placing a $ before the variable name will print the content the variable holds.

Clearing the Terminal

If any commands are entered in the Terminal, it stays there. To erase those commands, perform "clear" and press enter.

clear

Navigating through the Terminal

Before making files, it is preferred to create files in different folders or what is normally referred to as directories to be organized. Any existing files in the current directory can be seen by using the directory or 'dir' command.

To make a folder or directory in the Terminal, use the "mkdir" command. Any name can be given to it.

mkdir folder_name

To make more than one folder at a time, make sure to have spaces between each folder name and Bash will create many folders at once.

mkdir folder_name1 folder_name2 folder_name3

To delete any unwanted folders or directories, use the "rmdir" command.

rmdir folder_name1

To delete more than one folder at a time, make sure to have spaces between each folder name and Bash will delete the folders as specified:

rmdir folder_name1 folder_name2 folder_name3

Be careful specifying what folders are deleted since the Terminal instantly deletes what is specified.

To change directories, use the change directory or "cd" command alongside the name of the folder to enter the directory.

As shown below, the command dir was used to first show which files and folders are in each directory, and then the commands "cd Documents" and "cd Scripts" are used to first enter the Documents directory and then enter the Scripts directory that was created beforehand.

To enter a directory that the Terminal was previously in, use the "cd .." command to previously go back one directory

cd ..

To go to the home directory, use the "cd ~" command. The home directory is the default or starting directory when opening up the Terminal

cd ~

To go to any directory, use the "cd specify_entire_path_directory"

cd specify_entire_path_directory

The print working directory or "pwd" command shows the full path of the current directory. Every path should be written in the following format as shown by "pwd":

Making Files or Scripts

Below shows the current files in the Documents/Scripts directory by using the "dir" command. If there are no files, then nothing will appear.

A Bash script in the Terminal can be created by using the 'touch' or 'nano' command. 'nano' is used to edit the file after it was created, but it can also create the file if it does not exist. When making a file, the name of the file and also its extension can be created at the same time. To run a bash script, the .sh extension is needed.

After making the file, using "dir" shows the file is there:

If the touch command is used again to recreate the file, the command will execute and the file will not be overwritten.

Deleting Files or Scripts

If a new file with an unwanted name is created, it can be removed by using the rm command:

rm file_name

To delete more than one file name, make sure to have spaces between each file name similar to deleting many folders at once, and Bash will delete the files as specified:

rm file_name1 file_name2 file_name3

Be careful specifying what files are deleted since the Terminal instantly deletes what is specified.

Editing, Executing and Writing Files or Scripts

A file can be edited or created if it does not exist with the "nano" command

After using "nano", a text editor appears:

At the beginning of every script, a shebang is written to tell the Terminal that it is fully aware it is running a Bash script. The shebang can be declared by writing:

#!/bin/bash

Making Comments

In Bash, comments can be created by placing a '#' anywhere in the script. While comments are never executed when a bash script is run, comments are useful as they are used to write notes in a script to explain why another line of code is necessary.

# A comment is made by using a '#' and then writing some notes after the '#'
# This is an example comment

To save the script, press the two buttons together CTRL + S

To exit the script, press the two buttons together CTRL + X

Executing Scripts

To execute a script, type the word "bash" and the name and its file extension following it:

bash file_name.sh

After running the script, nothing happened since the contents in this file only include comments. Once again, comments are not printed out when a script is run.

Conditionals

Conditionals are often used to verify statements, below are a few keywords that are used with either the string or integer key type:

And: &&

Or: ||

Conditions to use with Numbers

-eq: Equal to

-gt: Greater than

-ge: Greater or equal to

-lt: Less than

-le: Less than or equal to

-ne: Not equal

Conditionals to use with Strings

">" : Greater than

"<" : Less than

\= : Equal to

!= : Not equal to

If, Elif, Else, Statements

Conditionals are often used with and to verify statements, and one type of statement is an if-statement.

If-Statement

if [ 3 -gt 2 ]
then
        echo "True"
fi

if [ 3 -gt 2 ]; then
        echo "True"
fi

  • "..." is a placeholder for a statement to be there

  • Bash is case and space sensitive with how any if statement is declared. First, "if" must be written, then hit space to enter a "[" and there must be a space between the variable or integer and the bracket, as shown with "[" and 3 and the rest of the entire statement. After finishing the statement, enclose it with the "]" bracket. "then" must be written on a new line or afterward write ";" next to the "]" bracket and "then" can be written on the same line. Within the if statement, hit "tab" to write the condition within the if statement. To close the if statement, the word "fi" is written on a new line.

If-Else Statement

To extend an if statement, an else statement can be added to print out an alternative statement if the statement that is being validated is not correct.

if [ 3 -gt 4 ]
then
        echo "True"
else
        echo "False"
fi

If-Elif-Else Statement

To check for many conditions without writing many separate if statements, many elif statements can be added. elif stands for else if. If the if-statement does not work, then an elif statement can be incorporated to check another statement. All of these statements begin with an if, in between have elif statements and the last statement is an else statement.

if [ 3 -gt 4 ]
then
        echo "False"
elif [ 3 -lt 4 ]
then
        echo "True"
else
        echo "Something went wrong."
fi

Using And, Or

The && symbol means and. The || symbol means or. These can also be used in verifying statements. For example, in an if-statement, is required to verify more than one condition is true, it is recommended to use the "&&" symbols.

if [ 3 -gt 2 ] && [ 2 -gt 1 ]
then
        echo "Both these statements are true"
fi

The "||" takes and reads many conditions, and will return a result if one of those conditions is true.

if [ 3 -gt 2 ] || [ 2 -gt 3 ]
then
    echo "True"
fi

While it is true 3 is greater than 2, it is also true 2 is not greater than 3. An or statement verifies that if at least one condition is true, in this case, 3 is greater than 2, it would print out what is specified in the "then" block.

Nested If Statements

A nested if-statement is including an if-statement within an if-statement. This is useful since in a normal if-elif-else statement, it will execute the first statement that is true and won't execute the other elif statements. Including an if-statement within an if-statement can be used if there was more code that needs to be run and verified only within the if-statement.

if [ 3 -gt 2 ] || [ 2 -gt 3 ]
then
        echo "True"

        if [ 3 -gt 1 ]
        then
                echo "This is true too"
        fi 

fi

For Loops

A for loop can searches through an entire variable and prints out long statements in a more readable way

just_a_string=("the [@]" "prints all words separated by spaces onto new lines")

for i in ${just_a_string[@]};
do
    echo $i
done

Not including the at sign will print the string as is.

A for loop can also print out many numbers within a specified range:

for i in {1..50..5}
do
    echo $i
done

While Loops

A while loop will always execute the statement as long as it is true. Using while loops is good to see how long the statement remains true, to exit out of the loop, it is recommended to either increase or decrease the variable to make the condition untrue and exit out of the while loop. To decrement or increment the variable, it must be placed within two parentheses.

i=3
while [ $i -gt 1 ]
do
        echo "The value of i is $i"
        ((i=i-1))
done

Functions

A function is declared by giving it a name, followed by a space, a parenthesis and a bracket. Within the brackets, code is written there. Instead of writing the same code over and over again to do a task, a function is recommended to hold that code to that desired task and call the function when needed.

function_name () {
        echo "You can write anything in here"
        echo "Write the name of the function at the end of the script, and it will execute"
}

function_name

Deleting Lines

Pressing both the CTRL + K buttons at the same time where the cursor is currently located, deletes an entire line of code in a script.