Bash Scripting Basics

No programming language is perfect. There is not even a single best language; there are only languages well suited or perhaps poorly suited for particular purposes. --Herbert Mayer

The default shell in most of todays linux distribution is Bash (Bourne-Again shell). A shell script is a "quick-and-dirty" of completing long and repetitive tasks in linux.

Shebang

The first line of a script which start with a #! is called a shebang. It indicates the interpreter of the script.

#!/bin/bash

In this case the interpreter of the script is bash located in /bin directory.

Make is Executable

It is a practice to keep the extension of the script as .sh but it actually doesn't matters. What matters is the the executable permission of the script. The Following commands can be used to to make the file executable.

chmod a+x myscript.sh  
chmod 755 myscript.sh  

Where should it be?

To make this script available to all users it has to be in users $PATH. This can be created in different directories as per requirement.

  • ~/bin/ - users private scripts (~ is the home directory of user)
  • /usr/local/bin - scripts available to all users on the system
  • /usr/local/sbin - scripts available to only root on the system

Variables

Defining a variable

CITY=Chicago  

a variable CITY has been created and assigned value "Chicago". To use this variable we can use $CITY or ${CITY}. If the variable is used in middle of the string where part of the string could be confused as part of variable name, user curly braces. Example:

echo I Live in ${CITY}.${STATE}  

Spaces? Take Care

Spaces should not be used before of after the = sign while assiging a value to a variable.

1) CITY =Chicago

Script tries to run "CITY" command with one argument, "=Chicago".

2) CITY= Chicago

Script tries to run "Chicago" command with the environmental variable "CITY" set to "".

Single or Double quotes

Quoting preserves white spaces.

CITY="New York"

echo $CITY # prints New York  
echo "$CITY" # prints New      York  
echo '$CITY' # prints $CITY  

Single quotes disables variable referencing.

Command Substitution

Command substitution reassigns the output of a command or even multiple commands by invoking a subshell. There are 2 ways of using it. Either by using the `backquotes` also known as `backticks` or by using (parentheses). Example:

MYHOSTNAME=`hostname`  

or

MYHOSTNAME=$( hostname )  

This substitutes the output of command hostname in the variable MYHOSTNAME.


Like it? Click here to Tweet your feedback

Swapnil Jain

RHCA Level IX, RHCI ♦ Solution Architect ♦ DevOps Trainer & Consultant