Linux Command Line Getting Started With Bash and Shell Scripting
Linux Command Line Getting Started With Bash and Shell Scripting
Travis Booth
© Copyright 2019 - All rights reserved.
The content contained within this book may not be reproduced, duplicated
or transmitted without direct written permission from the author or the
publisher.
Under no circumstances will any blame or legal responsibility be held
against the publisher, or author, for any damages, reparation, or monetary
loss due to the information contained within this book. Either directly or
indirectly.
Legal Notice:
This book is copyright protected. This book is only for personal use. You
cannot amend, distribute, sell, use, quote or paraphrase any part, or the
content within this book, without the consent of the author or publisher.
Disclaimer Notice:
Please note the information contained within this document is for
educational and entertainment purposes only. All effort has been executed
to present accurate, up to date, and reliable, complete information. No
warranties of any kind are declared or implied. Readers acknowledge that
the author is not engaging in the rendering of legal, financial, medical or
professional advice. The content within this book has been derived from
various sources. Please consult a licensed professional before attempting
any techniques outlined in this book.
By reading this document, the reader agrees that under no circumstances is
the author responsible for any losses, direct or indirect, which are incurred
as a result of the use of information contained within this document,
including, but not limited to, — errors, omissions, or inaccuracies.
Other Books by Travis Booth
Deep Learning Series
Deep Learning With Python: A Hands-On Guide for Beginners
The OS of Choice
Linux is an operating system that has been developed through collaboration
between communities of developers worldwide. Linux has been tested
rigorously in the IT industry and was found to be stable, easy to use, and
highly secure with a very powerful command-line interface. These and
many other advantages stated below are the major reason why people
choose Linux to power their Server infrastructure.
Linux OS Advantages
Linux operating system has many advantages that make it a solid choice for
server and other operating system functions.
Powerful Command Line Interface
Linux distributions have a powerful bash shell. The shell is also called the
terminal, and it affords users a text-only interface that gives them great
power.
High Security
Linux operating system is known to be very secure when it comes to
avoiding viruses and malware. The developers of Linux had security in
mind when they were developing the Operating System. The major reason
for this security comes from the fact users are expected to create and login
into Linux systems as a regular user. By default, most Linux distributions
like Debian and Ubuntu do not permit Root Login. Most people access their
Systems using limited regular accounts; which mean they have no
privileges that enable them to cause damage to the system. Linux regular
users can only cause damage to their own files.
The other major reason for Linux's greater level of security is that the
Operating System's source code is publicly accessible for review since
Linux is open-source software. The source code is accessed and reviewed
by a huge community of enthusiastic developers all over the globe, which
implies that most of the bugs and vulnerabilities have already been found
and are being continually found.
Greater System Stability
The Linux operating system is very sturdy and crashes less frequently.
Linux installations continue functioning well even after many years running
continuously. Indeed, some users have setups that were installed once and
had been running without incident for many years.
Linux servers in many data centers have high uptime, and their overall
availability nears 99.9 percent. Linux servers do not require reboots after
every system and program updates or patches. This sturdiness and high
uptime have resulted in the bulk of the Internet running Linux servers in
their infrastructure. ZDNET website estimates that a whopping 96.3 percent
of the best Web servers are running on Linux.
Easy to Maintain
Maintaining Linux involves regular updates to the programs running on the
system. Systems are regularly monitored and checked for bugs and
vulnerabilities. Updating programs ensures that bugs are fixed, new features
are added, and vulnerabilities are plugged. Linux is very easy to maintain
even for beginner users. Experience Linux users and administrators are able
to make central updates and program patches. Operating systems need a
way to check for vulnerabilities continuously. All Linux distributions have
their own central program repositories, where program code is audited and
tested regularly for bugs and any other reported issues, the software
repositories are used to keep the system up to date and safe. Linux
distributions offer regular system updates and no reboots are done after
system updates. As a Linux user, it is possible for you to schedule system
updates at regular times. Bash scripts and Linux Cron jobs are written to
automate the processes of scheduling system updates.
Can be Run on any Piece of Hardware
Linux operating systems have efficient use of system resources, which
include CPU and RAM. Linux uses the computer system's hardware
resources effectively and efficiently. This efficiency means that you can run
your Linux installation on any piece of decent hardware. Linux systems are
running on a variety of architectures from low-specked computers to mobile
phones and smaller gadgets.
Free to Use
Getting a Linux operating system is 100 percent free except for a few
Enterprise Distributions, which charge for Support like Red Hat and
Canonical. Linux is totally free of charge; users can download Linux and be
good to go with decent skills. Linux has all the basic programs required by
a typical and expert user available. Businesses and Governments can
leverage the cost of the Operating system and build robust infrastructure at
a significantly lower budget. Whole Internet ecosystems from DNS, DHCP,
Email, and Communication are setup on Free Linux for free.
100 Percent Open Source
Linux is an operating system developed by a community of developers, and
the source code of this operating system is freely available for users to
make contributions through documentation, finding and fixing bugs. This
community involvement means that there are many eyes that are auditing
and working on the system to make it stable and error-free. Users are free to
download the source code and modify or even distribute it.
Easy to Use
Linux operating system has increasingly become the mainstream. Linux is
now user-friendlier and has a simple and intuitive graphical user interface
(GUI) that makes it useable even by novice users. Contrary to the general
view that Linux is only for geeks, it is now being used on laptops and other
gadgets. Someone used to Windows can now easily move and use Linux on
their Personal Computers. The GUI has evolved to the extent that, without
understanding any shell scripts or code, most of what typical users want can
be accomplished on Linux as readily as is done on Windows.
Linux is Flexible for Customization
Linux has gifted all its users, from beginners to advanced administrators,
the flexibility to change the look and feel of their environment to suit their
requirements. We have more than three desktop environments such as
GNOME, KDE, Unity, Cinnamon, and MATE.
Linux has a large pool of alternative system and application programs that
users may select to install on their distributions.
Global System Support Available
Over the Internet, there is a powerful Linux Open source community that
provides support for Linux through different forums. Any question posed in
forums will generally be answered quickly as many enthusiastic Linux
volunteers are online and working to fix the issues. Also accessible for
business enterprises is the paid support option, with businesses such as Red
Hat and Canonical providing 24-7 assistance for critical installations and
services.
Linux Disadvantages
Linux operating system has a number of disadvantages of which the most
mentioned is that it is difficult for most people to learn to use the operating
system. The biggest disadvantage in Linux is that most hardware
manufacturers build their device drivers for Windows, so the Linux user has
to handle the programming of hardware drivers. Linux has an inherent lack
of driver support.
Linux infrastructure setups require that your administrators have a high-
level understanding of the operations of the operating system. Any
organization needs to ensure that they have the requisite Linux expertise
before they start using it.
The other disadvantage of Linux is the lack of a standard universally
accepted distribution across the globe. There are varieties of Linux
distributions that operate differently and manage things uniquely. This may
be daunting for most users
.
Chapter One: Linux Command Line
In this chapter, we are going to dive deep into the Linux Command Line Interpreter. We are going to
concentrate on the Bash shell and its environment. We will have a brief introduction into the
command line Interpreter, Shell, and Bash. I will guide you with regards to how to begin Bash
programming.
Example Commands
To check the default shell for a USER in the Computer please type the following command in your
terminal and check if your result resembles one below:
[ppeters@rad-srv ~]$ cat /etc/passwd
ppeters:x:500:500::/home/ppeters:/bin/bash
In Linux users are able to switch from one shell to the other. The user switches their shell by just
typing the name of the shell of choice. If you just type the name, your System will locate the folder
where the shell you have chosen is located using PATH settings. After typing the name of shell and
pressing enter, a new prompt is usually shown, since each shell has its own appearance:
[ppeters@rad-srv ~]$ sh
sh-4.1$
What is Bash?
BASH, also known as ‘Bourne-Again SHell' is the default user shell on Linux systems. Bash is
primarily a command-line interpreter who has traditional programming language constructs. In many
circles Bash is treated as a programming language albeit with logic peculiar to Bash. Bash as a
programming language has to support for variable constructs, functions and with program decision
flow control constructs like conditional statements and loops.
BASH shell prompts are depended on the privileges of the logged-in user. There is a dollar sign ($)
prompt for all regular users. Linux operating system has many other types of shells, each with its own
prompt, for example, csh has % as the prompt. All privileged users like the root user have unique
prompts; they have the# as the prompt. (Petersen, 2008).
Bash as the command line interpreter keeps all commands that are entered into the terminal as strings
and has no concept of numbers unless a user has instructed it to do arithmetic calculations. Bash
operates in a simplified way as follows:
1. Bash takes the user's keyboard input and separates it into words basing on white spaces (space or
tab).
2. Bash then assumes that the initial word from the user input is always a command . Bash then
takes everything that follows after the first word as arguments to be passed to the command.
3. After parsing and splitting the user input Bash then tries to process the command and add
arguments if they are available.
Getting Started with Bash
Linux has a number of Distributions that are available for selection to users. All these Linux
distributions have the bash as the default shell. Before working through this book, it is important to
make a choice of your Distribution. I encourage the reader to choose Centos 7 Operating system.
After choosing your Linux Distribution, it is important to know which command line-based text editor
you are going to use.
The writer recommends installation of VIM (VI Modified) editor on your Linux Server. Installation is
different in Centos and Ubuntu.
Vi is a popular and extensively used text manipulation editor among Linux system administrators.
Although Vi is widely used, it is tough to learn for novice Linux users primarily because it operates in
two different modes, namely the insert mode and the command mode . The insert mode is where
users normally type text in a file, and command mode is where your keyboard input is interpreted as
commands to perform on the text.
Setting up the Environment
Linux is a very flexible and customizable system. You can set the environment settings and variables
that define how your shell is going to function. You can allow the system to automate something that
you find yourself repeatedly setting or changing.
The Shell Profile
For any Linux user, there's a ~/.profile file in the user's home directory. It is in this .profile file that
you can personalize user settings attached to their profile. When the command-line interface is
initialized the following steps happen,
● /etc/profile is executed first
● Then the /etc/bash.bashrc file if your default shell is bash is executed, then
● ~/.profile , file is processed and
● Finally, ~/.bashrc file is executed lastly.
The~/.profile file is executed by any of the available shells, so it is important to put generic settings in
this file. All bash-specific settings should go in the ~/.bashrc file.
System administrators can set bash environment variables and aliases in the .bashrc file and even run
commands. All the files listed under the user's home directory that are prefixed with a dot are called
"dotfiles ."
Environment Variables
Linux allows the use of environment variables to change the way the Linux system functions. In the
command line, you can set Environment variables on the terminal, or statically by adding an entry
into the~/.bashrc file. The bash shell has four customizable prompts, namely PS1, PS2, PS3, and PS4.
PS1 Prompt
PS1, also known as Prompt String 1 , is the basic in-built customizable bash shell variable displayed
before each bash command in Linux. Customizations done to the prompt include adding and
modifying elements, changing background colors. Below is the default bash prompt.
The prompt above is displaying that the user has username ppeters and is logged into a server with
hostname "rad-srv ," and the user is currently working in the /var/log folder.
PATH
The bashPATH environment variable is configured to direct the shell to the location of the most
common programs, and user-created scripts that need to be executed. The default paths for most of the
common Linux system commands is/bin , /sbin ,/usr/bin , and /usr/sbin . Users can build their own
custom scripts in/usr/local/bin ,$HOME/scripts , and $HOME/bin . All user custom scripts'
directory path has to be appended to the PATH so that it will be easy to locate them through the shell
even when you are in a different folder: PATH=${PATH}:${HOME}/bin
Whenever you do not append the custom script path to the PATH environment variable, you may have
to provide either an absolute or relative path to the command. As an example:
Linux security best practices do not recommend putting a dot (.) in your PATH, especially prefixing
your PATH with a dot .
Users are encouraged to avoid appending a colon at the beginning or end of the PATH, or a pair of
colons separated by nothing, as that has the same effect as a single dot (.). Find below the example
PATH=$PATH :${ HOME}/bin
rather than:
PATH=${HOME}/bin:$PATH
File System Navigation
In Linux, everything is a file from programs, processes, devices, and directories. One of the most
important command-line functions is navigating the Linux file and directory structure. We have a
number of inbuilt bash commands which can be used to navigate through a Linux directory. Linux
uses a Hierarchical File Structure which starts at the root directory (/) moving down to files or leaves.
We basically have three major commands utilized in file navigation, which are
● pwd : This acronym stands for Print Working Directory. This command displays the current
working directory that a user is in.
[root@rad-srv ~]# pwd
/root
cd: CD is a command to move or jump from one directory to the next. CD Stands for Change
Directory.
[root@rad-srv ~]# cd /var/log
[root@rad-srv log]#
ls : The LS command is used to display contents of a directory.
[root@rad-srv sysconfig]# ls
anaconda console grub kdump network rdisc rsyslog snmptrapd sysstat.ioconf atd cpu
power init
Introduction to Directories
A directory is a file whose major function is to store file names and their related details. Directories or
Folders in Linux, whether they are ordinary, special, or directory, contain all files.
Linux operating system uses the hierarchical structure to organize files and directories. The Directory
tree is the name given to this structure in Linux. The directory tree starts with the single root node, the
slash character (/ ), and every other folder falls under the root directory.
Linux operating system has three basic types of files, namely regular, directories, and special files.
Regular Files are those files that contain text, data, or program code/scripts. Directories are a type of
file also called folders that contain or store both special and regular files. Linux directories are the
exact equivalent to folders in Windows. We also have what are called Special Files in Linux. These
special files give us access to a number of hardware devices such as hard drives, keyboards, monitors,
CD-ROM drives, USB flash devices, and Ethernet adapters.
Listing Files in Directories
System administrators in Linux do a lot of troubleshooting and use a number of tools. We have a tool
to display a list of folders and the files stored in the current directory; we use the ls (listing)
command:
[ppeters@rad-srv ~]$ ls
This ls command is used with a number of options such as the -l option, which gives more details
about the listed files:
[ppeters@rad-srv ~]$ ls -l
total 8578999
drwxrwxr-x 2 ppetersppeters4698 Sept 2 09:59
-rw-rw-r-- 1 ppetersppeters45371Sept 2 08:38 12.jpg
drwxr-xr-x 2 ppetersppeters5659 Sept 1 2019folder1
drwxr-xr-x 2 root root 4096 Sept 1 2019folder2
[ppeters@rad-srv ~]$
The ls –l command gives us the long listing of the contents of the file or directory. The ls –l command
displays more information, andso let’s break it down more.
The first character to the far left represents the type of the file. Reading from the output above, we
have character d, which represents a directory and – (hyphen) represents a regular file. Just next to the
first character in the output we have the File Permissions column. There are nine characters in this
column broken down into 3by3 fields, which represent user, group, and global file permissions. The
nine characters are broken down into three character batches with each three-character batch having
read, write, and execute permissions. In the output above the first rwx represents read, write, and
execute permissions assigned to the owner of the file. The second r-x for folder 1 means that group
ppeters has read and executed permissions but no write permissions to folder1.
The next or second column in the output is Number of Links field. For folder1, there are two links.
The third column or field displays the owner of the displayed file. In our example above, the owner is
ppeters. The fourth column is a display of the group to which the owner of the file belongs to. The
fifth field is the Size column. This column specifies the size of the file in bytes. The sixth field or
column is the Last modified date & time. This field specifies the date and time of the last
modifications done to the file. The last column is the name of the file.
The output of the ls –l command shows the type of the file in the first character of the output result.
From the example above, we have – and the d characters. The table below details all the types of files
that we have in Linux and their associated symbols.
Meta-Characters or Wildcards
We have characters in Linux that are useful when we are dealing with regular expressions. The
following characters; * (star) and? (Question mark) are called wild card operators or Meta characters.
The* symbol is used to match zero (0) or more characters, and the question mark (? ) is used to match
with a single character.
Illustration
[ppeters@rad-srv ~]$ ls pp*.doc
Displays all the files, the names of which start with pp and end with .doc :
ppeters01.doc ppeters02.doc ppeters03.docppeters04.doc ppeters05.doc
The example above shows that, * works as wildcard character that matches any character. To display
all the files that end with just .doc , users can use the following command:
[ppeters@rad-srv ~]$ ls *.doc
● The Single dot (.) is a representation for the current working directory.
● The Double dot (..) is the representation for the parent folder.
File Creation using VI Command
When working on the command line interface, we can use the vi editor to create regular files on any
Linux file system. Example command to create a file called ppeters_file:
[ppeters@rad-srv ~]$ vi ppeters_file
The command given above opens a file with the given filename ppeters_file. To get into insert mode
, the vi mode in which to edit the file you press key i . Once the user is in edit mode, they can start
typing their data or script in the file as in the following program:
This is P Peters’s file. It was created today at 12 noon.
We are going to store this text in this file.
Once a user is done entering their text in the file, they follow the steps below:
● Enter the esc key to exit the edit mode.
● Press Shift + ZZ keys simultaneously to exit the file completely.
You will now have a file created with filename ppeters-file in the current working directory.
After copying the command creates an additional file, there is going to be one more file ppeters_copy
in your current working directory. This file is going to bathe exact replica of the original file
ppeters_file .
Through the rm command, we are capable of deleting multiple files at once by just appending the files
that need to be deleted to the rm command.
[ppeters@rad-srv ~]$ rm file_name01 file_name02 file_name03
[ppeters@rad-srv ~]$
[ppeters@rad-srv ~]$
The mkdir command above creates the directory mydir_peters in the /tmp directory. The command
mkdir displays no output for successful creation or execution of the command.
You may create multiple directories on the command line, using mkdir by just listing each of the
directories. For example:
[ppeters@rad-srv ~]$ mkdir docs_dir public_dir
The statement above creates the docs_dir and public_dir directories under the current working
directory.
Creating Parent Directories
Linux command line gives system administrators the ability to create different directories from parent
directories to the child folders. When you want to create a child directory, but the parent directory is
not there, you use mkdir with –p option or switch to first create the parent folder before creating the
ensuing child directory. When the –p option is not specified the mkdir command displays the
following error message:
[ppeters@rad-srv ~]$ mkdir /tmp/ppeters/test
mkdir: Failed to make directory "/tmp/ppeters/test";
No such file or directory
Below is an example illustrating how to create parent directories in Linux:
[ppeters@rad-srv ~]$ mkdir -p /tmp/ppeters/test
The above command creates all the required directories, including the parent.
Removing Directories
In Linux you do not delete directories that contain files and other directories using the rm command
but can be deleted using the rmdir command as shown below:
[ppeters@rad-srv ~]$ rmdir dir_name
Note : Whenever you want to delete a directory, you have to ensure that it is empty, meaning there are
no other folders and files inside.
It is possible to delete many directories in one go as follows:
[ppeters@rad-srv~]$rmdir dir_name1 dir_name2 dir_name3
[ppeters@rad-srv~]$
The command deletes the directories dir_name1, dir_name2, and dir_name3, only if they don't
contain any files or folders. There is no console output when the rmdir command executes
successfully.
Renaming Directories
The bash mv (move) program is used to rename directories. The syntax is shown below:
[ppeters@rad-srv ~]$ mv olddirname newdirname
[ppeters@rad-srv ~]$
You can change a directory name from mydirname to yourdirname as follows:
[ppeters@rad-srv ~]$ mv mydirname yourdirname
[ppeters@rad-srv ~]$
VARIABLE2=100
for TOKEN in $*
do
echo $TOKEN
done
Below is the example run of the bash script above:
[ppeters@rad-srv ~]$./peters_test.sh James Jonesis Old
James
Jones
is
Old
Special Note : The do...done is a looping structure that will be detailed later on.
ARR_NAME[1]="Peter"
ARR_NAME[2]="Martin"
ARR_NAME[3]="Samson"
ARR_NAME[4]="Linda"
The syntax of an array initialization, using the bash shell, is shown below:
arrayname=(value01 ... valueN)
ARR_NAME[0]="James "
ARR_NAME[1]="Peter"
ARR_NAME[2]="Martin"
ARR_NAME[3]="Samson"
ARR_NAME[4]="Linda"
ARR_NAME[0]="James "
ARR_NAME[1]="Peter"
ARR_NAME[2]="Martin"
ARR_NAME[3]="Samson"
ARR_NAME[4]="Linda"
echo "Our Method One: ${ARR_NAME[*]}"
echo "Our Method Two: ${ARR_NAME[@]}"
The result of the bash script:
[ppeters@rad-srv ~]$./peters_test.sh
Our Method One: James PeterMartinSamsonLinda
Our Method Two: James PeterMartinSamsonLinda
Shells in Linux particularly bash supports a number of operators. This section will discuss in detail
the different operators.
In Linux bash shell there are arithmetic, Relational, Boolean, String s and File Test Operators.
Originally the shell did not have a mechanism to perform arithmetic operations; it used external
programs, like awk or expr .
The example below illustrates how to add two digits:
#!/bin/sh
val_add=`expr 5 + 9`
echo "The Total added value is: $val_add"
The result of the script above:
The Total added value is: 14
There are a number of points to be considered while performing addition −
● We should have spaces between the operators and the expressions. For instance, 6+9 is incorrect; it
should be written as 6 + 9.
● The arithmetic addition expression should be put between back ticks‘.‘
Bash Arithmetic Operators
The table below shows all the arithmetic operators.
Assuming that the variable x holds eight and variable y holds 15:
The table below shows all the bash arithmetic operators.
In bash scripting all the conditional statements should be put inside spaced square brackets. For
instance, this illustration [ $x <= $y ] is the correct format whereas, the following illustration [$x <=
$y] is wrong.
Bash Boolean Operators
Bash shell supports a number of Boolean operators as shown in the table below.
Assuming variable x holds 20 and variable y holds 40:
Boolean Operators Table
Operato Description Example
r
! This operator is called the logical negation. It [ ! false ] is true.
inverts a condition into its opposite value.
-o This operator is called the logical OR . If one of [ $x -lt 40 -o $y -gt 100 ] is true.
the two operands’ value is true, then the condition
is true.
-a This operator is called the logical AND . If both [ $x -lt 40 -a $y -gt 100 ] is false.
operands are true, then the condition returns true
otherwise it is false.
do
b="$x"
while["$y"-ge 0]# this is the inner loop loop2
do
echo -n "$y "
b=`expr $y - 1`
done
echo
a=`expr $x + 1`
done
This script will produce the result below. Please note how echo -n functions here. The -n option
ensures that the echo command does not print the command line new line symbol.
Bash Loop Control
The upcoming section is a discussion of bash control structures for looping for example break and
continue statements. We have looked at creating loops and working with loops to automate different
jobs. There are instances when you should exit a loop or jump over some parts of the loop. At such
instances, we use the break and continue statements to control looping.
The Break Statement
The Linux break statement is a bash shell construct that is used to stop an entire conditional loop from
execution after finishing the execution of all code units leading up to the break statement. When the
loop finishes, it steps through to the other sections of the code.
Break Statement Syntax
Break statement example
break
We use the example above to exit from nested loops.
break n
Above the argument, n represents the n th enclosing loop to be exited from.
Break Statement Example
Below is an example that shows a loop terminating as soon as x becomes 8 −
#!/bin/sh
x=0
while[ $x-lt 10]
do
echo $x
if[ $x-eq 8]
then
break
fi
a=`expr $x + 1`
done
We have the nested loop example below. The bash script below shows us that the program code exits
out of the first and second loops if varname1 equals 13 and varname2 equals 10 −
#!/bin/sh
do
for varname2 in09
do
if[ $varname1 -eq 13-a $varname2 -eq 10]
then
break13
else
echo "$varname1 $varname2"
fi
done
done
NUMBERS="8 9 10 11 12 13 14"
When it meets an expression containing one or more special characters, the shell performs the
substitution.
Substitution Example
The substitution illustration below shows that the variable is assigned a value, and the value is the one
that is printed on the terminal. This symbol is called the new line character, which essentially places
the cursor on the next line after the execution of the command "\n."
#!/bin/sh
x=20
echo -e "The variable X stores the value $x \n"
The script above will show us the result below. From the echo statement above we have -e switch
which enables bash shell to read and understand the backslash escape symbol. After executing the
script above, our result is as shown below.
root@bakyrie:~# vim variable.sh
root@bakyrie:~# chmod u+x variable.sh
root@bakyrie:~# bash variable.sh
The variable X stores the value 20
root@bakyrie:~#_
When we remove the –e switch from our echo command, we the \n backspace character interpreted as
a string and printed with the rest of the statement.
root@bakyrie:~# bash variable.sh
The variable X stores the value 20 \n
root@bakyrie:~#
The echo printing command is used with a varied number of escape sequences:
We have the –e switch that is used to help bash shell in interpreting backspace escape characters. We
also have the –n switch which is utilized to disable the insertion of the new line when a statement or
string is printed to the terminal screen.
Bash Command Substitution
Bash shell Command substitution is the feature that enables the shell to process a command and has
resulting output of that command to substitute the text of that command itself, or the output is sent
back to the terminal as an argument to another command.
Bash Command substitution is the process by which bash executes a set of instructions and then
substitutes the commands with that output from processing.
Substitution Structure
The structure of the substitution command is illustrated below.
`command`
The backquote character is used when performing command substitutions.
Example
Command substitution is usually used to assign command output to a variable. The examples below
show the substitution of the command:
#!/bin/sh
DATE=`date`
echo "TheDate today is $DATE"
USERS=`who | wc -l`
echo "The number of users who are logged inis $USERS"
UP_TIME=`date ; uptime`
echo "The system Uptime is $UP_TIME"
The result of the execution of the above script:
Date is Thu Sep 5 03:59:57 CAT 2019
The number of users who are Logged in is 1
The system Uptime is Thu Sep 5 03:59:57 CAT 2019
03:59:57 up 10 days, 16:30, 2 user, load avg: 0.43, 0.47, 0.55
Variable Substitution
Variable substitution allows the shell programmer to manipulate the state-based value of a variable.
Table of all the possible substitutions −
1 ${var_sub}
This allows the Substitution of the value of var_sub .
2 ${var_sub:-word_sub}
If our var_sub is either null or unset, then the variable word_sub is substituted for variable
var_sub . The value of var_sub does not change.
3 ${var_sub:=word_sub}
If variable var_sub is either null or unset, the var_sub is set to the value of word_sub .
4 ${var_sub:?message}
If variable var_sub is null or unset, message is printed to standard error. This operator
finds out that variables are set correctly.
5 ${var_sub:+word_sub}
If va_sub is set, word_sub is substituted for var_sub. The value of var_sub does not
change.
Example
Following is the example to show various states of the above substitution −
#!/bin/sh
unset var_sub
echo ${var_sub:+"This is the default variable value"}
var_sub="The Prefix"
echo ${var_sub:+"This is the default variable value"}
echo "4 –The Value of the variable var_sub is $var_sub"
Standard Error
The standard error ("stderr") is similar to standard output and standard input, but the
major difference is that stderr is where error messages are taken to. Try catching a file
that doesn't exist to see some stderr output:
[ppeters@rad-srv ~]$ catfile-is-not-there
cat: file-is-not-there: No such file or directory
The output above looks just like normal stdout output.Let us try to change that output
using pipes:
[ppeters@rad-srv ~]$cat file-is-not-there | sed’s/Non existant/Train Squash/'
cat: file-is-not-there: No such file or directory
Reading from the example above, we have not changed the output result even after
introducing piping. With piping, the shell gets the standard output of the left side of the
pipe and introduces it as the input of the bash command positioned to the right side of
the pipe symbol. From the example above the error output from the cat command
redirected to standard error , and not to standard out , meaning that nothing went
through the pipe to sed.
Redirecting Command Output
After normal command execution the standard out and standard error, streams display
on the console terminal. This makes these outputs visible to the user on the console. In
normal Linux bash operations, we can redirect the stdout and stderr output streams to a
custom file using the > "greater-than" operator:
[ppeters@rad-srv ~]$ echo “Greetings World”
Greetings World
[ppeters@rad-srv ~]$ echo“Greetings World”> new-msg-file
[ppeters@rad-srv ~]$ catnew-msg-file
Greetings World
The illustration above shows that the second echo statement didn't display the statement
to the terminal console because the output was redirected to the file called new-msg-file.
The statement > new-redirect-file has mainly two functions:
● The output redirector creates a file called new-redirect-file if the file doesn't exist;
and
● it would replace new-redirect-file's contents with the new contents if the file was
already there
Now if the new-redirect-file was already there, and we did echo greetings> new-
redirect-file, it would now have only greetings in it. If you want to add more data to the
file by appending, you are required to use the >> operator:
[ppeters@rad-srv ~]$ cat new-msg-file
Hello there
[ppeters@rad-srv ~]$ echo hello out there again >> new-msg-file
[ppeters@rad-srv ~]$ cat new-msg-file
Hello there
hello out there again
Stderr
We can use file descriptors to duplicate output. To duplicate terminal output to a file
descriptor, we use the >& "greater than and ampersand" operator prefixed to the file
descriptor number. Below is the example:
# Redirecting stdout result to the stdout (File Descriptor 1)
[ppeters@rad-srv ~]$ echo"hi there people">&1
hi there people
# Redirect stdout to stderr (File Descriptor 2)
[ppeters@rad-srv ~]$ echo"hi there people">&2
hi there people
The example above is similar to redirecting output to a file, as we did a couple of
examples before, stdout and the other descriptors are known as special files that require
us to use >& instead of >.
The output above looks similar, but the changes are clear when we start piping our
output. Below is an example of what happens when redirections are done to stdout in
comparison to when they are done to stderr:
# Redirect to the stdout, going through the redirection pipe
[ppeters@rad-srv ~]$echo"some are redirections">&1 | sed"s/some/all/"
all are redirections
# Redirect to the stderr
[ppeters@rad-srv ~]$ echo“some are redirections”>&2 | sed"s/some/all/"
all are redirections
Common Use Cases for stderr, stdout, and stdin
Example of redirecting combined output to a file:
[ppeters@rad-srv ~]$./command file_name1 file_name2 file_name3 > log-filename
2>&1
[ppeters@rad-srv ~]$ cat log-filename
stderr file_name2
stdout file_name1
stdout file_name3
Chapter Three: Files
We will start with an introduction to file searching and a detailed look at the various search tools
available. I will then discuss file archiving and the various ways of creating archives.
There are six unique ways to search for files in the Linux command line, and each of the ways has its
advantages. In this section of the book, we are going to look at the various search tools, namely;
locate, which, find, whatis, whereis, and apropos . These tools have their unique features and
merits; these search utilities are used for different purposes.
Linux commands for searching and finding files are varied, and each command performs well at
other areas than the other tools. This section will detail the various search commands and look at
their strengths in searching. Below we will start with a very brief introduction to these search tools
before we go into full details of each tool.
A Basic Introduction to Search Tools
Linux administrators may need to know the location of a file or directory on the filesystem but may
not know where to find it. There are six bash commands that can be used to search for it, including
whatis, whereis, find, and locate, apropos and which.
Introduction to Find
Below is the syntax of the find command:
If the path for the file is not specified, the search when using find begins in the user's current
working directory and searches down into all the sub folders.
The find command has many options which are reviewable through use of the find manual pages.
The manual pages for the find command are found by entering man find at the bash terminal. The
most utilized option is the -name , which directs our find command to look for files and directories
with the specified string in their name.
The illustration of the find command above is a search for files in the root directory "/" with the
name "file_name" string in their search pattern.
The Locate Command
The command locate’s syntax is:
The locate command enables us to see each file or folder that has the search_pattern string contained
in the file or directory name. To locate a file or folder with search pattern "finger," enter the
following statement:
[ppeters@rad-srv ~]$locate pwd
The bash locate command makes use of the slocate data store to search for files and folders with the
search pattern string "finger" in their names.
The locate command searches for strings patterns faster when the locate database is recent. That
locate database is scheduled for auto-updates by running a cron task every night. In Linux Cron job
is a small utility that executes in the terminal background, executing a variety of scheduled
responsibilities, for instance, making locate database updates at 6 am every morning.
The updated b command refreshes the slocate database on the command line interface.
The above which statement returns the path of the binary, or executable, bash commands.
[ppeters@rad-srv ~]$which cd
/usr/bin/cd
[ppeters@rad-srv ~]$
The whereis command illustration below returns the paths of the find command, the binary file of the
find command, the location of the source code, and the location of the find man page.
[ppeters@rad-srv~]$whereis find
/usr/bin/find /usr/share/man/man1p/find.1p.gz /usr/share/man/man1/find.1.gz
[ppeters@rad-srv ~]$
[ppeters@rad-srv ~]$whatis lp
The options switch takes control of the actions and the find process' optimization technique.
● The find_path feature defines where find begins its search, especially at the Linux root directory
for the search string.
● Statement from the syntax above takes control of all the tests that filter through the Linux
directory tree to give an output.
Take a look at the illustration below:
[ppeters@rad-srv ~]$find –O2 -L /var/www/html -name "*.php"
This find command statement enables optimization at the maximum level (-O2) and lets the find
command to follow soft links (-L) which are also called symbolic links. The find command traverses
the whole /var/www/html directory tree for files that end with .php.
\ The initial find command returns a listing of all files that have the search string zone at the end and
were altered four days prior. The second find command filters the test user's home directory for all
files that have names that end with the string conf and were altered in the previous six days.
Using Grep to Search
The find command can only filter the hierarchy of the directory depending on the name and metadata
of such a file. We use a tool like grep if you need to search for text or content within a file. The
instance below illustrates the use of grep:
[ppeters@rad-srv ~]$ find /etc -type f -exec grep "conf" '{}' \; -print
The above statement searches each object that is of type file specified by the "-type f" switch in the
/etc directory and then executes the grep "conf" command to find all the files that have "conf" text
string in them for each object file that meets the criteria. The matching files will be displayed on the
terminal screen using the (-print) switch. For finding match outcomes, the curly braces"{}" are used
as a placeholder. The curly braces {} are contained in single quotes (') to prevent the handling of a
malformed file name by grep.
To prevent shell interpretation, the -exec command is terminated with a semicolon (;), which should
be fled (\ ;).
This type of command could have used the xargs command to produce a comparable output before
the-exec option was implemented:
[ppeters@rad-srv ~]$ find /etc -name "rc.local" -exec chmod u+r '{}' \;
The statement above searches in the /etc folder for files that have the name rc.local and then executes
the chmod g+r program to change permissions of the file to give users' group the read rights to any
instance of rc.conf found.
The bash commands that run with the -exec option are executed in the find process' folder. Using the
-execdir ensures that the command is executed in the folder in which the match result resides. This
solves the security issues and produces better operations performance.
The -exec and –execdir switches run without additional prompts in the bash shell. It is possible to
replace -exec with the option -ok and replace the alternative -execdir with -okdir if you require
prompts before you take any action.
Searching and Deleting Files
This -delete option in find should be utilized with extreme caution because the action is irreversible.
In Linux, you may append the option -delete to the end of a match expression to delete all files that
match the find pattern. The -delete option should only be used when you are very certain that the
output results match only the files that you need to delete.
In the following example, the find command locates all files in the filesystem hierarchy beginning at
the current working directory and traversing into the directory tree. In this example, find will delete
all files that end with the characters .backup:
If the filename was given as a command in the bash shell, it returns the pathnames of the files (or
links) that would be executed in the current environment. It does this by searching the location for
executable files matching the arguments ' names in the PATH environment variable. The, which
command ignores all soft links.
0Status 0 means that all filename s in the search pattern were found, and all
were executable.
1Status 1 means that one or more filename s were not located, or were not
executable.
2Exit status 2 means that an invalid option was specified in the which
command
Which Example
[ppeters@rad-srv ~]$ which bash
The command above searches the pathname of the file which would be run if the bash command
were executed. The result of the command above is:
[ppeters@rad-srv ~]$ /bin/bash
The basic usage of the whatis command is simple. The user passes the tool name as input, and whatis
will search and display a one-line description of the command utility.
Here's an example:
[ppeters@rad-srv ~]$ whatis ls
The following output was produced by the aforementioned command:
-u This option helps in searching for all unusual entries. Linux files are said to
be unusual if they do not have one entry of each requested type. As
example, "whereis -m -u * " is searching for files in the current working
directory which do have documentation.
-B This option alters or otherwise puts a limit to the paths where whereis
looks for binaries.
-M This option alters or otherwise puts a limit to the locations where the
command whereis searches for manual pages sections.
-S This option changes or otherwise puts a limit to the places where whereis
searches for command sources.
-f This option terminates the past folder listing and informs of the beginning
of file names, and this must be utilized only when any of the -B , -M , or -S
options are in use.
Example apropos command: Let’s assume that you would like to archive or compress a file but
you don’t know the command to use to archive a file then you could type the apropos command in
the terminal and it will display all the related commands and a short description of their
functionality.
After running the apropos archive command below you will find a number of commands listed on
the terminal that have something to do with file archiving.
[ppeters@rad-srv ~]$ apropos archive
apt-secure (8) - Archive authentication support for APT
ar (1) - create, modify, and extract from archives
Archive::Zip (3pm) - Provide an interface to ZIP archive files.
Archive::Zip::FAQ (3pm) - Answers to a few frequently asked questions about A...
Archive::Zip::MemberRead (3pm) - A wrapper that lets you read Zip archive mem...
Archive::Zip::Tree (3pm) - (DEPRECATED) methods for adding/extracting trees u...
deb-extra-override (5) - Debian archive extra override file
deb-override (5) - Debian archive override file
dpkg-deb (1) - Debian package archive (.deb) manipulation tool
dpkg-split (1) - Debian package archive split/join tool
funzip (1) - filter for extracting from a ZIP archive in a pipe
gpg-zip (1) - encrypt or sign files into an archive
llvm-ar (1) - LLVM archiver
llvm-ar-3.8 (1) - LLVM archiver
phar (1) - PHAR (PHP archive) command line tool
phar.phar (1) - PHAR (PHP archive) command line tool
phar.phar7.1 (1) - PHAR (PHP archive) command line tool
phar7.1 (1) - PHAR (PHP archive) command line tool
ptardiff (1) - program that diffs an extracted archive against an une...
ptargrep (1) - Apply pattern matching to the contents of files in a t...
ranlib (1) - generate index to archive.
swipl-rc (1) - SWI-Prolog resource archiver
tarcat (1) - concatenates the pieces of a GNU tar multi-volume archive
unzip (1) - list, test and extract compressed files in a ZIP archive
unzipsfx (1) - self-extracting stub for prepending to ZIP archives
x86_64-linux-gnu-ar (1) - create, modify, and extract from archives
x86_64-linux-gnu-ranlib (1) - generate index to archive.
zip (1) - package and compress (archive) files
zipgrep (1) - search files in a ZIP archive for lines matching a pat...
zipinfo (1) - list detailed information about a ZIP archive
Options
Option Description
-d, --debug This option displays all the information about debugging.
-v, --verbose This option displays on the terminal console the verbose
warning messages.
-r, --regex This option parses and Interprets each keyword as a regular
expression. This is normally the default action. Each of the
keywords will be matched agains page names and the
manual page descriptions individually. The matches are not
bound to word boundaries.
-w, --wildcard This option parses and Interprets each of the keywords as a
string pattern with all the shell-style wildcards or meta
characters. Each of the keywords will be matched against
the existing page names and the manual page descriptions
individually. If the argument --exact is also utilised, then
output result match will only be located if the expanded
keyword string or pattern matches the whole description or
Linux manual page name. Otherwise, the keyword is also
allowed to match on word boundaries in the description.
-e, --exact With this option each keyword will be matched exactly
against the manual page names and the ensuing manual
page descriptions.
-a, --and This option only outputs the items that match all the given
keywords . The default output result is to display all items
matching any keyword .
-l, --long This option ensures that we do not trim the result to fit the
terminal console width. In most normal cases, the output
will be trimmed to fit the terminal width to avoid
malformed results from badly-written manual pages’
NAME sections.
-s list , This option only searches the given manual pages sections.
--sections list , The given list is a colon- or comma-separated list of
--section list manual pages sections. If an entry in the manual pages list
is a page section, for example "4 ", then the listed output of
descriptions will show all the pages in sections "4 ",
"4python ", "4x " etc; whilst if a listing shows an
extension, for instance "5perl ", then the resulting list will
include pages only in that exact part of the section of the
manual.
-m system [ ,...], -- This option is used to search in the other operating system
systems=system [ ,...] that the user has access to. For instance, to filter the manual
page descriptions of an operating system called "MacOS",
we use the option -m MacOS . The specified system can be
a combination of comma-separated names of operating
systems.
-M path , --manpath=path This option is used to specify an alternate set of colon-
separated manual page tree to filter. By default the
$MANPATH environment variable is used by apropos ,
unless it’s empty or not unset, in which case it will
determine an appropriate "manpath" based on your $PATH
environment variable. This –M option overrides the
contents of $MANPATH .
-L locale , The apropos command normally determines the current
--locale=locale system locale by making a call to the C procedure called
the setlocale which searches various environment
variables, possibly including $LC_MESSAGES and
$LANG . We may temporarily override the determined
value using the –locale option. This option is used to
supply a locale string to apropos command . Note that
locale option does not take effect until the search for the
manual pages actually starts. Result such as the help
message will always be output in the initially set locale.
-C file , --config-file=file Use this user configuration file rather than the default of
~/.manpath .
-h, --help This option helps in displaying a help message and exit.
-V, --version This option shows the version information.
Environment
SYSTEM Setting the $SYSTEM environment variable, has the same
effect as if it this variable was specified as the argument to the
-m option.
MANPATH Setting the $MANPATH environment variable, will have its
value interpreted as the colon-separated manual page tree
search path.
MANWIDTH Setting the $MANWIDTH environment variable, makes sure
that the value is used as the terminal width (as discussed in the
--long option). If this variable is not set, the terminal console
width will be calculated using ioctl if it is available, the value
of the $COLUMNS environment variable , or it falls back to
the default 80 characters if all else fails.
POSIXLY_CORREC If this environment variable called the
T $POSIXLY_CORRECT is set, to a null value, the default
apropos search will be an extended regular expression (-r ).
Compressing is very helpful when storing valuable files and sending large files across the Internet.
Compressing an already compressed file adds additional overhead, so you'll get a marginally larger
file. Stop compressing a file that is already compressed. Linux has many programs for compressing
and decompressing files. I’m now going to discuss the two most used utilities for compressing and
decompressing files.
Compressing and Decompressing Files
The most common tools used to compress and decompress files in Linux operating systems are gzip
and bzip2.
Extracting Archives
We can extract a tar archive whilst we are in the same directory it is located in by just executing the
tar command below:
[ppeters@rad-srv ~]$ tar xf example_dir.tar
It is also possible to extract a tar archive file in a folder in a different location by using the capital C
or the "C" flag in our options part of the command. For instance, the tar statement below extracts the
specified tar archive in the /usr/local directory.
[ppeters@rad-srv ~]$ tar xf files_dir.tar -C /usr/local
Alternatively, go to the /usr/local directory and extract the archive, as shown below.
[ppeters@rad-srv ~]$ $ cd /usr/local
[ppeters@rad-srv local]$ $ tar xf ../example_dir.tar
There are instances when you may want to extract files of a specific type. For example, the following
command extracts the ".jpg" type files.
[ppeters@rad-srv ~]$ tar xf example_dir.tar --wildcards "*.jpg"
Creation of compressed gzipped and bzipped archives
Tar command creates the .tar archive file by default. It is important to note that the tar command is
useable with the file gzip and bzip2 compression tools. The archive file that ends with the .tar
extension refers to the uncompressed tar archive. The .tgz and tar.gz extensions represent gzip
compressed archive files, whilst the .tbz and the file extensions refer to bzip compressed file
archive. The gzip and bzip2 archives are compressed archives.
Example creation of a gzip compressed file archive:
[ppeters@rad-srv ~]$ tar czf example_dir.tar.gz example_dir/
Or,
[ppeters@rad-srv ~]$ tar czf example_dir.tgz example_dir/
For all the illustrations above we compress the archives using z flag for the gzip compression
method.
The v flag is used with the tar command to enable the user to view the progress while creating the
archiv e.
[ppeters@rad-srv ~]$ tar czvf example_dir.tar.gz example_dir/
example_dir/
example_dir/wordfile.odt
example_dir/imagefile.jpg
example_dir/musicfile.jpg
The v flag above means verbose.
In Linux it is possible to create gzip compressed archive from a list of files:
[ppeters@rad-srv ~]$ tar czf files.tgz file_01 file_02 file_03
Or,
[ppeters@rad-srv ~]$ tar cjf example_dir.tbz example_dir/
Creating a bzip archive from a list of files:
[ppeters@rad-srv ~]$ tar cjf files.tar.bz2 file01 file02 file03
Or,
[ppeters@rad-srv ~]$ tar cjf files.tbz file01 file02 file03
The tar command above creates a compressed gzip archive of my $HOME directory, excluding
Documents and Pictures directories. To create a compressed bzip archive, replace z with j and use
the extension .bz2 in the above example .
List contents of archive files without extracting them
To list the contents of an archive file, we use t flag.
[ppeters@rad-srv ~]$ tar tf example_dir.tar
example_dir/
example_dir/wordfile.odt
example_dir/imagefile.jpg
example_dir/musicfile.jpg
To view the verbose output, use v flag.
[ppeters@rad-srv ~]$ tar tvf example_dir.tar
drwxr-xr-x ppeters/ppeters 0 2019-09-11 19:52 example_dir/
-rw-r--r-- ppeters/ppeters 9942 2019-09-11 13:49 example_dir/wordfile.odt
-rw-r--r-- ppeters/ppeters 36013 2019-09-11 11:52 example_dir/imagefile.jpg
-rw-r--r-- ppeters/ppeters 112383 2019-08-22 14:35 example_dir/musicfile.jpg
If the user wants to learn much more about the tar archive they may refer to the tar manual pages by
typing the command below.
[ppeters@rad-srv ~]$ man tar.
The example above created a zip archive named zip_dir.zip of the files_dir folder. This statement
only adds the parent directory to the zip archive. There are cases where you may need to archive all
sub-folders recursively; we use -r flag as illustrated below.
[ppeters@rad-srv ~]$ zip -r zip_dir.zip files_dir/
adding: files_dir/ (stored 0%)
adding: files_dir/text_file.txt (deflated 67%)
adding: files_dir/audio_file.mp3 (deflated 6%)
adding: files_dir/image_file.png (deflated 3%)
[ppeters@rad-srv ~]$
[ppeters@rad-srv ~]$ zip -r zip_dir.zip files_dir/ file_01 file_02 file_03
adding: example/ (stored 0%)
adding: example/Image.png (deflated 3%)
adding: file1 (stored 0%)
adding: file2 (stored 0%)
adding: file3 (stored 0%)
[ppeters@rad-srv ~]$
Unlike the tar archiving utility, the zip archiving and compression tool builds a zip archive and
compresses it when necessary. Tar utility only archives, and it does not compress.
Creating an archive with many directories and files
At times it is necessary to create an archive with more than one file and directories. We use the –r
switch with the zip command to recursively create the zip archive containing all the specified folders
and files:
[ppeters@rad-srv ~]$ zip zip_dir.zip file4
adding: file4 (stored 0%)
[ppeters@rad-srv ~]$
The illustration above has an existing archive and we are adding another file to the specified
zip_dir.zip archive. Looking at the zip program example above; the statement only updated the
contents of existing archive file without making any replacements. Whenever a user specifies an
existing file or folder archive, that existing archive gets updated and not replaced. This action only
preserves the existing archive. This capability to allow files to be added to a pre-existing archive is
an advantage of the zip program over the tar archiving utility.
Extract Zip archive files
Extracting archives is as simple as creating archives. To extract an archive, you need to type unzip
command and specifying the archive file you would like to extract:
Listing the contents of a zip archive is very useful when you want to determine the file(s) or folder(s)
you would like to extract instead of just extracting the whole zip archive. There are instances where
users need to determine which files they would like to extract or delete from an archive. It is at these
instances it is necessary to view or list the contents of a zip archive.
Creating an Encrypted rchive
The noblest feature of the zip utility is that it allows users to create an encrypted or password-
protected archive. With this encrypted or password-protected archive, users are required to enter
their password for them to be able to extract or view the contents of the archive.
Encrypting an archive, is achieved through the use of the -e flag.
[ppeters@rad-srv ~]$ zip -e -r zip_dir.zip files_dir/ file_01 file_02 file_03 file_04
Enter password:
Verify password:
adding: files_dir/ (stored 0%)
adding: files_dir/text_file.txt (deflated 67%)
adding: files_dir/audio_file.mp3 (deflated 6%)
adding: files_dir/image_file.png (deflated 3%)
adding: file1 (stored 0%)
adding: file2 (stored 0%)
adding: file3 (stored 0%)
adding: file4 (stored 0%
[ppeters@rad-srv ~]$
When an archive is created with encryption you need to enter your password when extracting or
viewing the contents of the archive.
[ppeters@rad-srv ~]$ unzip zip_dir.zip
Archive: zip_dir.zip
[zip_dir.zip ] files_dir/text_file.txt password :
[ppeters@rad-srv ~]$
The following output will appear after executing the above command.
Variables
Any programming language requires variable declaration. Variables of Bash
can be declared in various ways. If a value is allocated in a variable then at
the start of the variable no symbol is used. The symbol'$' is used with the
name of the variable when reading the variable value. Variable can be used
on the shell terminal or may be used in a bash script.
The commands below are declaring a variable of type string called
myvariable with a specified value, and then we print the value of the
variable in the terminal.
$ myvariable="Bash is cool"
$ echo $myvariable
Output:
[root@BAKYRIE:~# ]myvariable="Bash is cool"
[root@BAKYRIE:~# ]echo $myvariable
Bash is cool
root@BAKYRIE:~#
Please create a bash script file with the following contents. Declare two
variables here. These two variables are $x and $y . We need to ascertain if
the input value, which is stored in $x is equal to the value stored in $y. Then
the following message, "The two Numbers are equal " will be displayed
otherwise "The numbers are not equal " will be displayed to the terminal
screen.
var_numbers.sh
#!/bin/bash
echo "Please enter any number"
read x
y=23
if [[ $x -eq $y ]]
then
echo "The two numbers are equal here"
else
echo "The two numbers here are not equal"
fi
SampleOutput:
After running the script as shown below by line 3 we get the result below:
[root@BAKYRIE:~# ]vi var_numbers.sh
[root@BAKYRIE:~# ]chmod u+x var_numbers.sh
[root@BAKYRIE:~# ]./var_numbers.sh
Please enter a number:
16
The two numbers here are not equal
[root@BAKYRIE:~# ]./var_numbers.sh
Please enter a number:
13
The two numbers here are not equal
[root@BAKYRIE:~# ]./var_numbers.sh
Please enter a number:
23
The two numbers are equal
root@BAKYRIE:~#
The above var_numbers.sh script were executed three times with values 16,
13 and 23.
Conditional Statement
You can use conditional statement in bash like just another programming
language. If-then-else' and' case' statements are primarily used in any
programming language to implement condition statements. The use of a
conditional statement is shown in this chapter of this tutorial by using the'
if' statement. Create a bash file where a conditional statement is used with
the following script. Here, the user will take two values as input and store
$code and $age in the variables. If' is used to verify the $age value is higher
than or equal to 18, and the $register value is 1100. If both circumstances
are valid, another message will be printed, "You are qualified to see the
film." will be printed otherwise "You are not eligible to see the movie "
will be printed.
conditional.sh
#!/bin/bash
echo "Please enter your code"
read code
echo "Please enter your age"
read age
if [[ $age -ge 20 && $code -eq '3300' ]]
then
echo "You are allowed to watch this movie"
else
echo "You are not allowed to watch this movie"
fi
Sample Output:
After taking distinct input values, the following output will appear. 1200 is
provided as a code, and 19 is provided as the age for the first script run and
if the condition returns completely untrue. 3300 is also provided as a code,
and 23 is provided as the age of the second phase, which returns a true
condition.
[root@BAKYRIE:~# ]vim conditional.sh
[root@BAKYRIE:~# ]chmod u+x conditional.sh
[root@BAKYRIE:~# ]bash conditional.sh
Please enter your code
1200
Please enter your age
19
You are not allowed to watch this movie
[root@BAKYRIE:~# ]./conditional.sh
Please enter your code
3300
Please enter your age
23
You are allowed to watch this movie
root@BAKYRIE:~#
Loops
When executing various parts of the script, the loop is used to do the job.
Like other languages, Bash supports three kinds of loop statement. The
three-loop statements are for loop, while loop, and until loop. A specific
loop is used in the script based on the programming demands. In this
chapter, the uses of these three loop types are shown using straightforward
examples.
Using for loop
We will generate a bash script file with the bash script where for iteration
we use the' for' loop. The' for' loop is used primarily to iterate an input list
or array. A list of the name of the weekday is used here and every name of
the weekday is iterated using the loop. The' If ' conditional statement is used
to print a specific statement depending on the name of the weekday.
forloop.sh
#Read the name of a day of the week in each iteration of the loop
for day in Monday Tuesday Wednesday Thursday Friday Saturday Sunday
do
#Check whether the day of the week is either a Monday or Thursday
if [[ $day == 'Monday' || $day == 'Thursday' ]]
then
echo "Training on $weekday at 9:30 am"
#Check whether the day of the week is Tuesday or Wednesday or Friday
elif [[ $day == 'Tuesday' || $day == 'Wednesday' || $day == 'Friday' ]]
then
echo "Seminar on $day at 11:00 am"
else
#Print ‘Holiday’ for other days
echo "This day $day is a Holiday"
fi
done
Output:
Run the script.
[root@BAKYRIE:~# ]chmod u+x forloop.sh
[root@BAKYRIE:~# ]./forloop.sh
Training on Monday at 9:30 am
Seminar on Tuesday at 11:00 am
Seminar on Wednesday at 11:00 am
Training on Thursday at 9:30 am
Seminar on Friday at 11:00 am
Saturday is a Holiday
Sunday is a Holiday
root@BAKYRIE:~#
until_script.sh
#!/bin/bash
#Initialize the variable, x
x=50
#Repeat the loop until the value of $x is greater than 10
until [ $x -lt 10 ]
do
#Check whether the value of x is odd
if [[ $x%2 -gt 0 ]]
then
echo $x
fi
#Increment the value of x by 1
((x=$x-1))
done
The script will print all odd numbers between 50 to 10. The following
output will appear after running the script.
[root@BAKYRIE:~# ]vim until_script.sh
[root@BAKYRIE:~# ]chmod u+x until_script.sh
[root@BAKYRIE:~# ]./until_script.sh
49
47
45
43
41
39
37
35
33
31
29
27
25
23
21
19
17
15
13
11
root@BAKYRIE:~#
Functions
In essence, a Bash function is a collection of commands that can be used
and reused in scripts many times. The aim of a function is to assist you to
increase the readability of your bash scripts and prevent writing the same
code over and over again.
Bash functions are somewhat restricted compared to most programming
languages. We'll explain the basics of Bash functions in this section and
demonstrate you how to use them in your shell scripts.
A bash method or procedure is basically a number of instructions, which
can be called repeatedly. The aim of a function is to make your bash scripts
readable and to prevent the same program from being written over and over.
Bash methods are somewhat constrained in comparison to traditional
programming languages. We present the basics of Bash functions in this
section of the book and demonstrate their use in your bash shell scripts.
Function Declaration in Bash
The structure of declaring a bash function is intuitive. Bash functions are
declared in two diverse ways:
1. The first format begins with the name of the function, followed by
brackets () also known as parentheses. This is the format of choice and the
most frequently used format.
function_name () {
commands
}
Function Single line format 1:
function_name () {commands;}
The second function syntax begins with the function reserved word
followed by the name of the function.
function function_name {
commands
}
Function Single line format 2:
function function_name { commands; }
When a code block has to run numerous times in a script, the function is
used to do the job. You will only need to call the function by name if you
need to perform various times the script specified in the feature rather than
adding various times the same script. First bracket start and end is used with
the name of the feature to declare the feature in bash script. The method can
be called in bash by just the name of the function. As another conventional
programming language, Bash does not support function argument. But in
this section, the value can be handed to bash function in a distinct manner.
With the return statement or without using the return statement, the value
can be returned from the function.
Create a bash file with the script below to learn how to declare and call the
functions in the bash script. The basic_function.sh script below declares
three different functions. The first procedure or function to print a basic
message, "Bash scripting for beginners," is declared. The 2nd function is
defined to assign a string value after calling the procedure in a variable,
$return_str which will print, "Learn bash scripting here."
basic_function.sh
#!/bin/bash
#Declaring a basic procedure/method/function
function display_string()
{
echo "Bash scripting for beginners"
}
#Declaring a method/function to return a string value
function str_data()
{
#Initializing a variable with initial string value
str_data="Start bash scripting today"
}
#Declaring a procedure/method to read the entered argument
function circle_area()
{
#Read the input arguments
local radius=$1
circle_area=$(echo $radius*$radius*3.14 | bc)
#Display the area of a circle to screen
echo "The area of the circle given radius $radius above is $area"
}
#Invoke the function to display a string of characters
display_string
#Invoke the method to assign a string to a variable
string_data
#Display the variable string to screen
echo $string_data
#Read value of the radius entered
echo "Please enter your radius size"
read rad
#Invoke the function to create area with radius size
calculate_area $rad
call_function.sh
#!/bin/bash
1st_script="sum_script.sh"
2nd_script="deduct_script.sh"
3rd_script="product_script.sh"
4th_script="/home/ppeters/code/divide_script.sh"
source "$1st_script"
bash $2nd_script 50 20
echo "Enter the value of x"
read x
echo "Enter the value of y"
read y
eval bash $3rd_script $x $y
exec $4th_script 30
Creating Menus
Bash has a helpful command to generate a useful menu called the
command' select.' Using this command, different menu kinds can be
produced. This command uses a specific info list to generate a menu.
Use the vim command to create a menu_script script file with the example
script code below. The menu_scipt.sh script file is an illustration of how to
use the ‘select' command to create a menu of options in bash.
The menu_script script file shows a list of five menu items that will be
displayed as a menu in this instance, prompting the user to select any
language from the list. The selected value is stored in the $linguistic
variable and subsequently printed by concatenating with another string. The
bash program will frequently request that the language be selected awaiting
the user to press the termination menu choice 6 to exit the menu_script.sh
program.
menu_script.sh
#!/bin/bash
#Display this message for the user
echo "Please choose your favorite language"
# Make language list for the menu item
select language in Perl C++ Javascript Bash C# Exit
do
#Display the chosen value
if [[ $language == "Exit" ]]
then
exit 0
else
echo "Your chosen language is $language"
fi
done
According to the example output below, the user pressed four initially that
printed Bash then pressed 5 for the second time which displayed the C#,
then pressed 1 for Perl and lastly pressed 6 to exit the program.
[root@BAKYRIE:~]# chmod u+x menu_script.sh
[root@BAKYRIE:~# ]./menu_script.sh
Please choose your favorite language
1) Perl
2) C++
3) Javascript
4) Bash
5) C#
6) Exit
#? 4
Your chosen language is Bash
#? 5
Your chosen language is C#
#? 1
Your chosen language is Perl
#? 6
done
The commandlinescript.sh script above is run for four times using four
different types of arithmetic operators. The following output will appear for
the argument values, 12 + 6, 12 – 6, 12 x 6 and 12 / 6 . The result output
below shows all the inout and the results.
[root@bakyrie:~]# vim commandlinescript.sh
[root@bakyrie:~]# chmod u+x commandlinescript.sh
[root@bakyrie:~]# ./commandlinescript.sh 12 + 6
Your argument values are: 12 + 6
Your operation result is = 18
[root@bakyrie:~]# ./commandlinescript.sh 12 – 6
Your argument values are: 12 – 6
Your operation result is = 6
[root@bakyrie:~]# ./commandlinescript.sh 12 x 6
Your argument values are: 12 x 6
Your operation result is = 72
[root@bakyrie:~]# ./commandlinescript.sh 12 / 6
Your argument values are: 12 / 6
Your operation result is = 2
[root@bakyrie:~]#
Arguments are used in bash, and they are passed to the name-value pairs in
bash.
WE would like you to create a commandline2.sh bash file, with the
following script to demonstrate how to read argument values using their
name. The command-line bash script will read two argument variables. The
named argument values are printed in the script's first statement.
Next, a loop will be used to iterate the array containing the value of the
command line argument. By using the' cut' command, each element in the
array is separated into a key-value pair. Next, a case statement is used to
print a particular message based on the key value.
commandlinescript2.sh
.# !/bin/bash
#Display the list of argument variables
echo "Your argument values are: $1 $2"
#Read each argument independantly using for loop
for arg in "$@"
do
#Separate the argument name and the value
key=$(echo $arg | cut -f1 -d=)
value=$(echo $arg | cut -f2 -d=)
#Display a message based on argument’s name
case $key in
name) echo "The Student’s name is $value";;
mark) echo "The obtained mark is $value" ;;
*)
esac
done
The result below shows the output from executing the
commandlinescript.sh, the script is supplied with two command-line
arguments which are; name= "James Jones" and mark=83. The two
command-line arguments are split by the script, and the resulting two values
are displayed on the screen.
root@bakyrie:~# vim commandlinescript2.sh
root@bakyrie:~# chmod u+x commandlinescript2.sh
root@bakyrie:~# ./commandlinescript2.sh name="James Jones" mark=83
Your argument values are: name=James Jones mark=83
The Student’s name is James Jones
The obtained mark is 83
root@bakyrie:~#
From above all the arithmetic operations are executed through the use of
double brackets. We may use ‘let', ‘expr ' and ‘bc ' commands to do
arithmetic operations in bash.
Manipulating Bash Strings
The string data in bash can be used to perform many types of tasks. Some
are string concatenation, string comparison, string splitting, string case
change, etc. There are no bash built-in string functions to do the string
operations like in other standard programming languages. The section of
this book discusses some common string manipulations.
String Concatenation
String concatenation is the process of adding two or more strings together.
Strings are joined together in bash by appending one string after another.
We can create a bash file with the following script to show the use of string
concatenation. We will initialize two string variables and display them after
combining the two string variables. The example shows that the content of
$stringcat01 and $stringcat02 will be merged and printed.
stringconcat.sh
#!/bin/bash
#Initialize first string variable
stringcat01="This user "
#Initialize second string variable
stringcat02="Loves Bash Scripting"
#Display the output after combining both string variables
echo "$string1$string2"
String Comparison
To make string data comparisons, bash uses a unique kind of comparison
operators. We are going to create a bash file with the script below to
demonstrate how two strings are compared. In the stringcompare.sh script, a
string value is read from the standard input as an input and is compared to
the other string. If the first string value matches, then a message is
displayed, "You can program in Python" or "You can program in PERL."
stringcompare.sh
#!/bin/bash
echo “Enter any string value”
read text
#Check the input data is equivalent to “Python”
if [ $text == "Python" ]; then
echo "You can program in Python."
else
echo "You can program in PERL"
fi
stringcase.sh
#!/bin/bash
#Initialize the 1st text string
textstr1='[email protected]'
#Print the value of $textstr1 by converting all characters to uppercase
echo “${email^^} ”
#Initialize the 2nd text string
textstr2=’Bash scripting basics’
#Print the value of $textstr2 by converting all uppercase to lowercase
echo $textstr2 | tr [:upper:] [:lower:]
Reading string data through the loop
The string data functions for any programming language as a character
array. In this section of the book, we discuss how the ' for ' loop is used to
read text string data in bash. Create a bash script file with the content script
below to use a loop to read each portion of the text string value.
readstring.sh
#!/bin/bash
# using for loop to read each string
for value in Bash Programming for the Beginners
do
echo $value
done
firstscript.sh
#!/bin/bash
echo "Please enter a number"
read x
# Checkif the number you entered is less than or equal to 100
if [[ $x -le 100 ]]
then
exit 0
else
exit 1
fi
secondscript.sh
#! /bin/bash
#Run the bash file , firstscript.sh
bash "first.sh"
#Check if the return code is equal to 1
if [ $? -eq 1 ]
then
echo "The number you entered is greater than 100"
else
echo "The number you entered is less than or equal to 100"
fi
Output:
Run the script.
$ bash secondscript.sh
The following output will appear when the script is executed and passed the
values 56 and 110 one at a time.
#!/bin/bash
echo "Reading the hardwarefile.txt file using cat command"
# Read the content of the file using `cat` command
content=`cat hardwarefile.txt`
echo $content
echo "Reading the file line by line using loop"
# Assign the filename
filename='hardwarefile.txt'
# Each line of the file will be read by each iteration of the loop
while read line;
do
# print the line
echo $line
done<$filename
Output:
Run the following commands.
$ cat hardwarefile.txt
$ bash readfilescript.sh
From the illustration above the first command will display the contents of
the file, hardwarefile.txt without running any bash script and the second
command will run the script of readfilescript.sh and print the content of
the file for two times by using `cat` command and `read` command with
while loop.
root@bakyrie:/home/ppeterszw# cd
root@bakyrie:~# vim hardwarefile.txt
root@bakyrie:~# vim readfilescript.sh
root@bakyrie:~# cat hardwarefile.txt
DvdRom
RAM
Monitor
Keyboard
Mouse
Scanner
Printer
root@bakyrie:~# chmod u+x readfilescript.sh
root@bakyrie:~# ./readfilescript.sh
Reading the hardwarefile.txt file using cat command
DvdRom RAM Monitor Keyboard Mouse Scanner Printer
Reading the file line by line using loop
DvdRom
RAM
Monitor
Keyboard
Mouse
Scanner
Printer
root@bakyrie:~#
Piping in Bash
A bash shell pipe is a way to connect the output of one command or
program to the input of yet another command without using any temporary
files to store the preliminary results of the previous command.
Syntax
1st_cmnd | 2nd_cmnd
1st_cmnd | 2nd_cmnd | nth_cmnd
1st_cmnd arg01 | 2nd _cmnd arg01 arg02
From the illustration above, we can easily join together all the three lines of
commands above and produce the same output result by running a single
command with pipes, as shown in the following example command. We do
not use a temporary file here to get the output result. The illustration below
shows the chaining of output from the sort command into the input of the
grep command and lastly the word count of the result from grep.
[root@bakyrie:~]# sort student_marks.txt | grep 'BSE-101' | wc
Output
The results of running the above-piped statement are the word count of
anything that contains the string "BSE-101" from the student_marks.txt file.
The word count firsts lists the number of occurrences of the string being
grepped "BSE-101" and also outputs the number of words in this instance
we have nine words and lastly displays the total number of characters in the
results which is seventy-nine in our example above. The output of the
command will be 3 9 79. Three entries of output with string "BSE-101", 9
words and 79 characters counted.
root@bakyrie:~# sort student_marks.txt | grep 'BSE-101'
Daina BSE-101 80
Sarah BSE-101 87
Susan BSE-101 72
root@bakyrie:~# sort student_marks.txt | grep 'BSE-101' | wc
3 9 79
root@bakyrie:~#
Create exercise02.sh
#!/bin/bash
str_info= “Having fun with shell Scripting!”
echo $str_info
Third Exercise:
This exercise is about using variables to store the output of the command
"hostname." Print "This script is running on the machine called _." where
"_" is the output of the "hostname" command.
Create exercise03.sh
#!/bin/bash
HOSTNAME=$(hostname)
echo “This script is running on the machine called $HOSTNAME”
Fourth Exercise:
This exercise is about creating a bash file used to determine whether a file's
path is in existence. When the script finds that the file path does exist, it
will display a message that the "file's path does exist." The next part of the
script checks to determine if you are able to write to the file. If the user has
permissions to write to the file the terminal screen will have a message,
"You have rights to alter the file's path." Otherwise, if you have no
permissions, display on the terminal console the message that "You do NOT
have permissions to edit file's path."
Create file exercise04.sh and input the script below
#!/bin/bash
USER_FILE=”/home/ppeters/exercises/test_file.txt”
if [ -e “$USER_FILE” ]
then
echo “The $USER_FILE path does exist”
fi
if [ -x “$USER_FILE” ]
then
echo “You have permissions to process $USER_FILE” else
echo “No permissions to process $USER_FILE”
fi
Fifth Exercise:
In this exercise the learner is expected to create a Linux bash script file
called exercise05.sh that displays on the terminal screen
"chihuahua","doberman","hound","basset","pitbull"and "corgie" on the
terminal screen with each one of the dog breeds appearing on a separate
line. The learner should do this in as few lines as possible.
Create exercise05.sh
#!/bin/bash
DOGS=”chihuahua doberman hound basset pitbull corgie”
for DOG in $DOGS
do
echo $DOG
done
Conclusion
Linux is a wonderfully diverse language and you should take the time to
explore it. Granted it might seem a bit ocmplex at first but with constant
practice, you’ll being to see why the mouse is overrated as a companion!
Jokes apart, my aim with this book has been to give you an introduction and
walk you through some of the most basic linux commands and features. The
idea is for you to work your way through the sample code at your own pace.
There are many applications Linux lends itself to and this is precisely what
my other books on the topic cover. For example, how would you like to be
an ethical hacker and start a career in network security and administration?
Linux truly is a programmer’s dream.
Hopefully you’ve enjoyed this under the hood look at what goes on with
Linux. I hope this book has been an enjoyable and informative erad for you.
Do let me know what you think and be on the lookout for the next book in
this series in which I’ll take you deeper into the world of Linux and bash
scripting.
I wish you the best of luck in your Linux learning adventures!
References
Negus, C. (2015). Linux ® Bible Ninth Edition (9th ed.). Wiley.
Petersen, R. (2008). Linux: The Complete Reference, Sixth Edition .
McGraw-Hill.
This le was downloaded from Z-Library project
Z-Access
https://wikipedia.org/wiki/Z-Library
ffi
fi