Console Into Mass. The Transit to the Light Side. Bash-scripting

Vitalii Rybka
Jan 26, 2017 · 6 min read

Introduction

A tool is convenient to use only if it helps solve a certain task. It’s also important that the tool is adjustable to particular user’s needs. An ability to expand it functionality would be an added bonus.

Finally, we’ve got on to one of the most interesting and fascinating topics — bash-scripting. Every time you launch a terminal, it automatically starts to run a shell command interpreter which understands and processes commands you’ve typed on a keyboard. A shell also signals errors and watches out for compliance of the commands with their syntax. Here are some of the examples of these commands: change directory, create a new directory, add a text file, edit a text file, save changes, etc.

The list of shell software is quite big today, yet sh is still recognized as the standard. Developed by Stephen Bourne in 1977 it was actually the first release of the command line interfaces that soon became a big success (wiki). In 99% cases, users working on OS *nix driven computers have bash as the default shell command interpreter. You could also find zsh shell, but let’s save this story for another time.

The important note. This article isn’t a full bash-scripting guide but a rundown of the bash-programming basics with examples. It should help readers learn some of the fundamentals to use in practice further on. In the end of the article I give some useful links with more detailed information on the subject.

The Basics

The first part will be all about the basics. We will look into the concept of scripting, see how to start a script, how to determine its variables and how to assign their values. I will also provide some tips on how to pass arguments to a bash script and work with them. The seconds part will be about the branching, while in the third one I will focus on cycles.

Whatever bash-based script you take, its first line will always be the same:

#!/bin/bash

This is also the way how we tell the command interpreter which application to run. To improve code portability, you could enter it this way:

#!/usr/bin/env bash

When done this way, you make it easier for the system to interpret the command correctly. This is also a necessary step to do if you often work on different OSes or PC. If not, the first command will work just fine. In all my examples I used it too.

All files that a user creates are not executable by default and require specifying this parameter by entering the command:

chmod +x <filename>

You could run a non-executable script too, by typing:

bash <filename>

Variables

Variable is a special area in computer memory with its own name that refers to a certain memory cell. As a rule, variables are used to hold information and comprise two key elements: a name and a value.

Name:

  • Letters, numbers, underline (_).
  • Cannot start with a number.

Value:

  • Numbers, strings (in double quotes if with spacings), characters.

How to create (overwrite) a variable:

path="$HOME"

Pay attention that we put spacing neither before nor after equal sign.

Reading variables:

"$path" or "${path}"

In most cases two variants work equally well. However, if the command hasn’t been interpreted correctly or looks confusing, you should stick with the "${path}" only.

Passing arguments to a bash script

./script.sh arg1 arg2 arg3 … argN

How to process arguments in a bash script:

It’s time to create the first script. As it is always the case, a user will see the welcome phrase “Hello, world!”.

This is how easy it is to show the work of bash script by such a simple example. Let’s consider a different example and practice a bit with variables and arguments, passing them to a script. All examples that I give in this article can be found in the repository.

Please, note, all bash-based scripts have a .sh extension.

Branching

So, now after we’ve already learnt some of the basics and practiced with variables a bit, let’s try to work with branching. For working with branches we will need to use the following statements:

  1. if
  2. if/else
  3. if/elif/else
  4. case/in/esac

The first three of them are pretty similar, each next line supplementing the other. Let’s have a look at the simplest one:

As you’ve noticed, there’s no semi-comma at the end of the lines. However, if you need to write statements (and not only) in one line, putting semi-commas will be necessary.

Working with branches, it’s also important to check whether the string is blank or not, if the number equals zero, whether we work with a file or with a directory, etc. To allow you to accomplish these and other tasks, bash utilizes its unique syntax. I figuratively divided it into four categories: strings, numbers, files and boolean. Let’s take a close look at each of them:

Conditions (strings):

Conditions (numbers/strings):

Conditions (files):

Conditions (boolean):

Let’s skip if/else statement but linger round if/elif/else:

The script expects to receive one output argument containing the name of a file or the name of a directory. After the checking of argument is done, you will know what to do next. If this is a true file or directory, you can delete it, if not, you will need to send a user a message that deletion isn’t possible.

Now, let’s get a look at the last statement in the branch — case/in/esac. If drawing analogy with JavaScript, it would be an alternative to switch/case directive. Here’s the example:

The given script expects to receive two numeric arguments: one and two, and depending on their order, it will create either file or directory. You will also need to run the check to see whether the number of arguments complies with the number typed in by a user and there are no less than two. If the arguments aren’t correct (which we can see from the value assigned by default), we send a user a message.

Cycles

In this part we will consider some of the examples how to work with cycles. To organize cycles, bash uses the following statements: for/in and while.

Here’s the example of for/in syntax:

Where i is the name of variable that an array will be passed to. During each next iteration i will gain the following array value.

The list of values comprises 1 2 3 4 5. Let’s run a cycle that will go through each of the values. Then create the variable file_name. Check next whether a file with the same name already exists. If not, you will need to create it, if it does, skip this step.

The word continue here is a keyword that allows skipping iteration and proceeding to work, while the word break allows stopping script execution. Both these words are used in the frame of if/else statement only.

Let’s see how the while statement works:

And consider the example:

In the given example the ninth and the thirteenth lines contained the key word read. As long as $again variable equal the value "yes" , the program will ask you to enter a user’s name in order output it on a screen. Then you will be asked if you want to proceed. You will receive these messages until you either enter any other line but "yes" or press Enter. Yet, the code in the ninth line containing $name being not declared before looks much more interesting. This is a dynamic variable that’s been created when the program is run.

Useful links

  1. bash-handbook
  2. Advanced Bash-Scripting Guide
  3. Shell Style Guide from Google
  4. Learn the Command Line
  5. The Command Line Crash Course
  6. Basic Unix commands

In conclusion

Let us end the introduction with bash on this positive note. The given information should be enough for readers to start working with simple scripts and automating most routine tasks.

With reference to my next article I’d like to tell readers that it will contain less theory but more examples on how to automate routine tasks with the help of bash scripts. Keep following up.

This is all for now. Thanks for your attention and special thanks to those who’ve read the article to the end. Meet you soon again!

Vitalii Rybka

Written by

Front-End Developer, Technical Writer, Speaker, Blogger var-bin.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade