Bash Scripting for Beginners Part I

S. Jackson
6 min readJun 10, 2020

This document is an introductory tutorial. I will be teaching the reader how to create bash scripts in the command terminal.

What will be discussed:

I comments

II using variables

III read user input

CREATING BASH FILE

When creating a bash script, you must first append the file with the location of your bash. To find the location of your bash, type the following in your terminal:

which bash

Once entered, an exact location of your bash should appear in your terminal. You’d need to copy this path for later use.

To create the file needed to run your script, first you must navigate to a directory you’d like to save the file in. For simplicity sake, lets save the file on your desktop.

There are many indirect ways to get to your desktop, but it’s impossible for me to know which commands to use without actually knowing where you are currently — so lets navigate to your desktop directly:

cd Desktop/

Desktop isn’t case sensitive, so this is the same thing:

cd desktop/

In programming, ‘/’ always represents the root of a directory. Root simply means top level. To elaborate on it a little further, the root is what holds all of the files. So you may have a directory called ‘myEmployees’ that may have files of each employee by name. The root directory is ‘myEmployees’ in this case.

Once at your desktop, lets create a file called ‘helloWorld’ like so:

touch helloWorld.sh

Once you’ve created this file, navigate to it from your choice of editor or IDE (mine is Visual Studio Code but literally any other will work fine ie. Sublime, Atom)

.sh informs the interpreter that this is a shell file.

In the helloWorld file, the first line of code should be the path to your bash. In most cases, the path to your bash will be:

/bin/bash

But, make sure this is the correct path by following the steps above. Now it simply isn’t enough to input that at the top of your file, you must also prefix it with a hash and what we call ‘bang’ — which is just a slang word to say exclamation mark. These two together (hash and bang) is called shebang (swear i’m not making this up) So, the file would look like this:

#! /bin/bash

COMMENTS

Comments are used more for human interpretation purposes, meaning they help us understand what the code is used for and/or doing. To create a comment in your shell file, you must first prefix it with a hash

# this is a comment

Unlike many coding languages, you can even add comments on the same line as actual code

echo ‘Hello World’ # this is a comment

In the case above, the code ‘Hello World’ will be executed and the comment will be ignored even though they are on the same line.

SYSTEM VARIABLES

System variables are created and maintained by your Linux or Unix operating system. Some system variables are:

$BASH ←- provides name of bash path

$BASH_VERSION ←- provides version of bash

$HOME ←- provides home directory

$PWD ←- provides present working directory

System variables are, in best practice, always capitalized. To print the information of a system variable simply use echo.

echo $BASH

Full list of system variables

USER DEFINED VARIABLES

These are variables that are created by the user. They can not start with a number. You do not need to prefix this variable with a dollar sign — since the dollar sign essentially tells the interpreter the reading of data is required. You assign a user defined variable like so:

name=Dre

value=10

Notice that although Dre would be encapsulated in quotes in other languages, there’s simply no need to in bash. So, quotes aren’t necessary. To print the values of the the name and value variable in the terminal, simply use echo:

echo $name

echo $value

Notice when attempting to read the information in the variables, a dollar sign is used — but not when assigning.

RUN YOUR PROGRAM IN THE TERMINAL

At this point, your file should have some information ready to be displayed in the terminal. To run your program, all you must do is enter the path to your program. For example:

./helloWorld.sh

When you hit enter, you should get a permission denied error. This is because when using the command touch it’s restricted to only read/write permissions and not execution. To change the permissions of your file you must input the following in your terminal:

chmod += name of file

So in this case it would be

chmod += helloWorld.sh

Now, try to run the program again — and as you can see, it displays variable values in the terminal.

READ USER INPUT

To read user input, you must use the read command followed by the variable name(s). When reading user inputted information, you can not assign a variable a value in the traditional sense. Instead, the interpreter automatically sets a value to a variable you provide prematurely. To make it make more sense lets look at it in action:

echo ‘What is your favorite food? : ‘

The above command will ask a user their favorite food

read favFood

The above command will assign whatever is inputted by the user to the variable favFood

echo ‘The users favorite food is $favFood’

The above command will print the users favorite food

READ MULTIPLE INPUT FROM USER

To store multiple inputs from a user, first you must propose a question and like the prior example, assign a variable — in this case multiple variables — that will be used to store information.

echo ‘Input first, middle, and last name’

read firstName middleName lastName

echo ‘Employee name : $firstName $middleName $lastName

The above program will prompt the user for their full name and print the name the user inputted. It’s important to note that when a user is inputting information, each value (name in this case) must be inserted on the same line.

ALLOW USERS TO INSERT DATA ON THE SAME LINE AS QUESTION

Now, if you’ve been following along you’ll see that after each question, users must insert their answers on the next line — for example:

$ What is your first name?:

(terminal prompts user to insert data on the next line line)

What this section is about is allowing users to insert data on the same line as the question like so:

$ What is your name?: (terminal prompts user to insert data on the same line)

In order to accomplish this, you must use the read keyword and a -p flag, ie:

read -p “username: “ user_name

echo ‘your username is $user_name

The above code lets the interpreter know that user data must be inserted on the same line as the question, and then it prints ‘your name is ‘ followed by whatever the user’s username is.

ALLOW USERS TO INSERT AND HIDE PASSWORD

To allow a user to insert a password and hide it’s contents, you must use the -sp flag. The way you use this flag is the same as the -p flag:

read -p “username: “ user_name

read -sp “password: “ user_psswd

echo ‘your username is $user_name’

echo ‘your password is $user_psswd’

One thing you may immediately realize is when you get to the password prompt, you start typing but do not see any characters — this is perfectly normal. Since you used the -sp flag, no characters will display on screen at the time of input but once you hit enter, the password will be saved in the user_psswd variable. The code above will display the contents of both the user_name and user_psswd variable.

EXTRACT INPUT AS AN ARRAY

To extract input as an array, you use the -a flag after the read keyword. You can store many inputs in one variable and access them as you would with any array — by using index.

echo ‘What is your full name? (first, middle, and last)’

read -a names
echo ‘Your first name is ${names[0]}’

echo ‘Your middle name is ${names[1]}’

echo ‘Your last name is ${names[2]}’

You must encapsulate the variable name and index with curly braces.

USER INPUT, NO VARIABLE

What happens when a user inputs a string but there is no variable? There’s a built in variable called $REPLY that it automatically saves in. The way you use this variable is simply by not naming a variable after the read keyword.

echo ‘What is your name?’

read

echo ‘Your name is $REPLY’

This is the end to Part I Bash Scripting Tutorial

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

S. Jackson
S. Jackson

Written by S. Jackson

Database Administrator | Web Developer | Software Developer

No responses yet

Write a response