facebook youtube pinterest twitter reddit whatsapp instagram

Getting Started With Bash (Introduction)

This is my first post on bash scripting, and I decided to delve into bash scripting because I am tired of doing repetitive tasks manually.

So, if you ask me why use bash? My answer would be, if you want to automate stuff you do manually, then you should join the bandwagon, say you want to automate setting up a full-blown website, and other crazy manual stuffs.

Having said that, let's get started with the basics...

Checking The Version of Bash

There are two ways you could check out the version of bash, the first way is using: bash --versionand the second way is to print the value of the bash version variable, and that is done using: echo $BASH_VERSION

I so much hate stress, so, I'll go with the first one, and the output is as follows:

devsrealm@server:/$ bash --version
bash --version
GNU bash, version 4.4.20(1)-release (x86_64-pc-Linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
devsrealm@server:/$

My version is 4.4.20 at the time of writing this guide.

Preparing Text Editors For Scripting (Nano)

At this point, I guess you have your preferred text editor, for me, I love nano because it's simple and easy to use.

Since we are scripting, and we would need some emphasis on certain code or function, we can for sure increase the usability and configuration of Nano.

There are two ways to go about the configuration, you can either do a user-specific configuration where a certain user only has that specific configuration, I'll show you how to do that in a moment or do a system-wide configuration where all your user has access to the same configuration, this is done in the /etc/nanorc file.

To do a user-specific configuration of Nano text editor, you create .nanorc in the user home directory:

touch ~/.nanorc && nano .nanorc

This would create and open the .nanorc in your user home directory, now let's add some cool configurations, if you want more configuration, you can check /etc/nanorc.

Add a linenumber: set linumbers, this is one of the features you'll be glad you have:

1. Set Linumbers in nano

Hit CTRL + X, and Y and Enter to save. Now open the same .nanorc file using nano .nanorc, and you'll see the beautiful line number ;) :

2. nano linenumbers set

Alright, you get the idea, at this point, I'll give you all the preferred configuration I go with, just copy and paste to the nanorc:

## This adds linenumbers
set linenumbers

## This auto indents
set autoindent

## Overwrite the default tab size, this Set width of a tab to #cols columns
set tabsize 4

## This will scroll line by line, instead of the default jagged behavior
set smooth

## Enables syntax highlighting for shell scripts
include /usr/share/nano/sh.nanorc

The ## are just comments, copy save and exit, and we are good to go with nano configuration, and at this point, I can say the editor is fairly usable for scripting ;)

Changing Command Path

The $path environment variable is a number of directories in which GNU/Linux will look for scripts and or programs.

GNU/Linux will only check for the executable in the path environment only when the full or relative path to the program is given, so, let's configure the path, and this would be done via .bash_profile, chances are it's not available in your shell. so, create and open using the following command:

touch ~/.bash_profile && nano .bash_profile

Add the following line in the file:

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

In layman, what the above command is saying, is Mr.Bash, please look into my home directory ($HOME) in a directory called (/bin), I have programs in there, and I want you to look into that folder whenever I run a program.

You know why this is useful, it is useful in the sense that the PATH variable prevents you from having to write out the entire path to a program or scripts every time you run it. Basically, it stores the shortcut to the program file.

To add another path you, just append a column, e.g PATH=$PATH:$HOME/bin:/usr/programs/bin

Save, and Close the file. To reload changes immediately without logout, enter source ~/.profile

Verify it using echo $PATH

Lastly, let's create a directory named bin in our user home directory, this would enable us to find the script by name without the file path:

test -d $HOME/bin && echo "Exist/Not Creating" || mkdir $HOME/bin

What the above command does is to check if a bin directory already existed in your user home directory, if it already exists, output "Exist/Not Creating", and if does not already exist, create the folder.

This is where we would create all our script.

Creating and Executing Your First Script

We have our ninja tools ready, and it's time to fight, joking off course. Let's start with the renowned Hello World!

Create and open up your first script: nano $HOME/bin/helloworld.sh

Add the following:

#!/bin/bash
echo "Hello World"
exit 0

This is a simple bash hello world script, so, let's understand what the full program is doing:

  • #!/bin/bash - This is always the first line of every bash script, and also known as shebang or hashbang. This looks like a comment, the difference is that it appends an exclamation mark to the comment. What this line does is to instruct the shell which interpreter to use to run the commands inside the script. If you are running a python script, you would use #!/usr/bin/python, Since we're writing a bash script, we used #!/bin/bash. you get the idea.
  • echo "Hello World" - echo is a built-in command that can be used to write or print to the screen, the information to print is enclosed in double-quotes. So, this basically says, print "Hello World" to the STDOUT; Standard output, or the screen
  • exit 0 - The exit command is used to exit the script, this is not compulsory at this stage, but a good idea to leave it there.

Executing The Script

Once you've saved the script, you will want to add an execute permission for the file.

Learn More About Permission

Before adding a permission bit, try running bash helloworld.sh

You'll be presented with "Hello World" but this is not a long term solution, so, to make the running easy from any location, add the following permission to the file:

chmod +x $HOME/bin/helloworld.sh

Now if you run helloworld.sh, you will be greeted with Hello World:

3. Hello World

Customizing The Script With Arguments

We can pass an argument to the script via the command line, to better explain this, let's first create a new copy of the script:

cp $HOME/bin/helloworld.sh $HOME/bin/hello2.sh

Add the permission bit: chmod +x $HOME/bin/hello2.sh

Now, modify the script as follows:

#!/bin/bash
echo "Hello $1"
exit 0

The $1 is waiting for you to pass an argument via the command line, so, let's try running the script and provide an argument as shown below:

4. Pass an Argument to a script

The below table shows more argument you could use:

Argument Identifier (Special Variable) Meaning
$1 to $n

$1 is the first argument, $2 is the second argument till $n nth arguments. Once you get to the 10th argument, you must enclose them in braces, e.g ${10}, ${11}, and so on.

$0 The name of the script itself and is often used in the usage
statements.
$# Total number of arguments passed to script
$$ Process id of the current shell
$* Refers to all arguments.
$? Exit status id of the last command
 $! Process id of the last command

Now, try adding $2 to the script, and pass 2 names. If you run it, it is only going to print out the second name:

5. Add $2 argument

To add 2 arguments, you can do

echo "Hello $1 $2"

To add every argument, just use $*

If you find yourself ina situation where you actually want to use the $ symbol, you can escape it using a backslash (\), this way it would convert it into the right format. E.g to print $USER is owing $50, you would do:

echo "$USER is owing \$50"

If the user is named "pascal", it would print:

Escaping speical variable

Play with the arguments, and I'll see you in the next guide where we dive even deeper.

Related Post(s)

  • sed (Stream Editor) In Bash Scripting

    Another powerful filter in GNU/Linux is sed (stream editor), which is a program for performing basic editing tasks on the output of another program or on a file. sed or stream editor can be used to p

  • awk In Bash Scripting

    Up until now, we have covered a couple of text processing, from sed to grep to sort, and now we have the big daddy, which is awk. awk (which stands for Aho, Weinberger, and Kernighan - its creators)

  • (Bash Script) Automate Multiple Classicpress & Wordpress Installation + [Caching and SSL]

    If you are tired of using control panels (I am because they are mostly not secure, and most comes loaded with bundles of useless stacks), and want to do everything on the server level, I wrote a menu

  • Returning Values From Functions in (Bash)

    In the guide function in bash, we dive deep in bash functions and we also pass some information into the functions to carry out a certain operation. In this guide, I'll show you how to get informatio

  • Functions in Bash

    Functions are modular building blocks for creating powerful and modular scripts, using function makes it easy to isolate a code since it would be in a single building block, which would be isolated f

  • grep (Regular Expression) In Bash Scripting

    We recently discussed filters in bash scripting, in this guide we would look more into the practical usage of using a filter program, and an example of such a program is grep. grep, in its simplest f