Shell (BASH) Scripting QuickStart Guide for Administrators

What is ShellScripting ?
  • Shell scripting is used to automate certain tasks, make processes easy for user such as installation, monitor system resources, etc.
  • Default linux shell is BASH -> Bourne Again Shell replacement for Bourne Shell. Written by Brian Fox.
  • It is basically an interpretter, which interprete our commands and convert it into binary for CPU to understand.
  • Bash also can read commands from file which is also called as Script.
  • Script is nothing but a sequence of commands in a simple ASCII text

How to write bash script ?
There are various components in shellscript. Major components are as below:
     1. Shebang Line
     2. Variables
     3. Statements

     4. Loop
     5. Functions
     6. Regular Expressions

Shebang Line:
#!/bin/bash --> Shebang line 
Every shell script starts with this Shebang line.
#!<interpreter> <options>
When I write a script abc.sh. In that I have mentioned shebang line as #!/bin/csh
Then when I execute that script by "./abc.sh", actually it will get executed like:
/bin/csh abc.sh
Please note that # is used to comment line in Shell scripting. If you want to any line just for information or not to execute then you should put '#' in the beginning of that line.
eg. test.sh
     #!/bin/bash --> Shebang line
     echo “Hello World”
And to execute it, Please go into the directory where that shellscript is stored and run below command on bash prompt
     ./test.sh
Variables & echo statement:
Variables are container and when we call it with $ that means we are opening the container and getting what is inside.
define varialbles by <variable>=value eg. var=123
getting variable value by using $ sign: echo $var

Reading keyboard inputs:
     echo -e "What is your name: c"
   read <variable_name> eg. read myname
To get value of “myname” use echo $myname

File Descripters and redirecting:
File Descriptors : 0 --> stdin Def:keyboard
                       
: 1 --> stdout Def:screen
                       : 2 --> stderr Def:screen
                       : /dev/null - Bit Bucket
To redirect output of command to a file
     command > /path/to/file
To redirect errors of command to a file
     command 2> /path/to/file
To redirect both output and errors to a file
     command > /path/to/file 2>&1
To hide output and error of command
     command > /dev/null 2>&1
Executing commands inside script using backtick:
     val=`uname -a`
     
echo $val ---> you will get output of 'uname -a' command.
“If” statement:
     if [ $var <operator> value ]
     
then

         <command>
     else
         <command>
     fi
     operators:
          -lt or < --> less than
          -gt or > --> greater than
          -le or <= --> less than and equal to
          -ge or >= --> greater than and equal to
          -eq or == --> equal
Please remember comparing variable with numerical value for maximum compatibility use -lt,-gt instead of symbolic operators.
 
“case” statement:
case $val in
     value1)

         commands
         ;;
     value2)
         commands
         ;;
      *)
         default commands
         ;;
esac
Function:
Function is a set of commands which are repeatedly require in same or different scripts
     To define function
         function_name() {
             command1

              command2
              ....
        }
     To call function in same script
              function_name
To call functions in other shellscript:
Write all required functions in one file & Call that file inside shellscript
     source </path/to/script name>
     
OR
     
 . </path/to/script_name>
 and call function name directly.
What is Retrun code $?
Whenever we execute any command, it stores an exit value to bash. That value is called return code.
if return code is 0 then command executed successfully or else command failed.
To get return code, give "echo $?" immidiate after executing command.
Eg. To test return code using if statement
     var=`echo $?` ---> Enter value of return code in Variable
     if [ $var == 0 ]
     then

          command
     else
          
command

     fi
Passing arugements to script .. $0 $1 $2
     <script_name> argument1 argument2                  |                  |                     |
                
$0               $1                  $2
So if I want argument1 should be used inside the script then
In script I should get the value of argument1 by using "echo $1" command.
Conditional expressions in if statement
     -a file    --> True if file exists.
     -b file    --> True if file exists and is a block special file.
     -c file     --> True if file exists and is a character special file.
     -d file    --> True if file exists and is a directory.
     -e file    --> True if file exists.
     -f file    --> True if file exists and is a regular file.
     -g file    --> True if file exists and its set-group-id bit is set.
     -h file    --> True if file exists and is a symbolic link.
     -k file    --> True if file exists and its "sticky" bit is set.
     -p file    --> True if file exists and is a named pipe (FIFO).
     -r file    --> True if file exists and is readable.
     -s file    --> True if file exists and has a size greater than zero.
     -t fd    --> True if file descriptor fd is open and refers to a terminal.
     -u file    --> True if file exists and its set-user-id bit is set.
     -w file    --> True if file exists and is writable.
     -x file    --> True if file exists and is executable.
     -O file    --> True if file exists and is owned by the effective user id.
     -G file    --> True if file exists and is owned by the effective group id.
     -L file    --> True if file exists and is a symbolic link.
     -S file    --> True if file exists and is a socket.
     -N file    --> True if file exists and has been modified since it was last read.
     file1 -nt file2    --> True if file1 is newer (according to modification date) than file2, or if file1 exists and                                     file2 does not.
     file1 -ot file2    --> True if file1 is older than file2, or if file2 exists and file1 does not.
     file1 -ef file2    --> True if file1 and file2 refer to the same device and inode numbers.
     -o optname    --> True if shell option optname is enabled. The list of options appears in the description of                                   the -o option to the set builtin (see The Set Builtin).
     -z string    --> True if the length of string is zero.

example 1 ++++ Checking file ++++:     if [ -f /var/log/messages ]
     then
         echo -e "Yes messages file is there"
     else
         echo -e "No messages file is not there"
     fi
example 2 ++++ checking strings +++++
     val=`df -h|grep neelesh`
     if [ -z $val ]
     then
          echo "Neelesh partition is not mounted"
     else
          echo "Neelesh partition is mounted"
     fi
“for” loop
     for varname in list
     do
          command1
          command2
     done
Here for, in, do, done are keywords.
list contain list of values
varname is any bash variable name
example 1: ++++
     for i in 1 2 3 4 5
     do
        echo "Welcome $i times"
     done
example 2: ++++
     for i in {1..5}
     do
          echo "Welcome $i times"
     done
example 3: ++++
     for i in {0..10..2}
     do
          echo "Welcome $i times"
     done
example 4: ++++
     for i in $(seq 1 2 20)
     do
          echo "Welcome $i times"
     done
example 5: ++++
     for (( EXP1; EXP2; EXP3 ))
     do
          command1
          command2
          command3
     done
     ------------------
     for (( i=1; i<=7; i++))
     do
          echo "Welcome $i times"
     done
“while” loop
     while [ condition ]
     do
         command1
         command2
         command3
     done
example 1: ++++
     x=1
     while [ $x -le 5 ]
     do
          echo "Welcome $x times"
          x=$(( $x + 1 ))
     done
example 2: ++++
Script.sh
     #!/bin/bash
     counter=$1
     factorial=1
     while [ $counter -gt 0 ]
     do
          factorial=$(( $factorial * $counter ))
          counter=$(( $counter - 1 ))
     done
     echo $factorial
Basic regular expressions:
A regular expression is a pattern that describes a set of strings.
Regular expressions are constructed analogously to arithmetic expressions by using various operators to combine smaller expressions.
Most characters, including all letters and digits, are regular expressions that match themselves. Any metacharacter with special meaning may be quoted by preceding it with a backslash.
Use of regular expressions provides the ability to perform multiple tasks at one time,
regular expressions save time and resources on a server. Instead of performing many passes
over the same text in order to achieve one goal at a time, you can achieve many goals using regular expressions.
     * – matches 0 or more times
     ? – matches 0 or one times
     + – matches 1 or more times
     [] – define character classes of one character [Bb]
     () – group characters and to provide alternation (mail | db), group text
     ^ – anchor text at start of line
     $ – anchor text at end of line
     | – matches alternate words
     . – match only one character
     – escapes following character
     {} - qualifier for max or min, max {1,6}
     Regular Characters include: A-Z, a-z, 0-9 and “_”.
example 1.
     tail me*.[1-3]
example 2.
     ps aux | grep -E 10[1-9][1-9]
example 3.
     ps aux | grep -E 10[1-9]{2}
    ps aux | grep -E 10[1-9]{4}
example 4.
     ls ?[[:digit:]][[:digit:]][[:digit:]]?

POSIX Character Classes. [:class:]
This is an alternate method of specifying a range of characters to match.
     [:alnum:] matches alphabetic or numeric characters. This is equivalent to A-Za-z0-9.
     [:alpha:] matches alphabetic characters. This is equivalent to A-Za-z.
     [:blank:] matches a space or a tab.
     [:cntrl:] matches control characters.
     [:digit:] matches (decimal) digits. This is equivalent to 0-9.
     [:graph:] (graphic printable characters). Matches characters in the range of ASCII 33 - 126. This is the         
                     same as [:print:], below, but excluding the space character.
     [:lower:] matches lowercase alphabetic characters. This is equivalent to a-z.
     [:print:] (printable characters). Matches characters in the range of ASCII 32 - 126. This is the same as
                     [:graph:], above, but adding the space character.
     [:space:] matches whitespace characters (space and horizontal tab).
     [:upper:] matches uppercase alphabetic characters. This is equivalent to A-Z.
     [:xdigit:] matches hexadecimal digits. This is equivalent to 0-9A-Fa-f.

And last but not least is "Here document":
It is a form of I/O redirction to feed a list of commands to interactive program or command such as ftp, usersadd, etc.
example:
     #!/bin/bash
     echo -e "Enter username to add: c"
     read var1
     echo -e "Enter desired password: c"
     read var2
     useradd $var1
     passwd $var1 <<EOF ###### Here document
     $var2
     $var2
     EOF 
I hope this document will help you learn basics of Shellscripting. Please do let me know your feedback on
Harshashetty4u@gmail.com
+91-8976827112

Comments

Popular posts from this blog

Firewall in Ubuntu Linux

25 Linux Interview Questions and Answers (Basic and Scenarios)

Basics of LDAP & OpenLDAP