Skip to content

Latest commit

 

History

History
234 lines (205 loc) · 8.11 KB

6.ShellScripting.md

File metadata and controls

234 lines (205 loc) · 8.11 KB

Shell Scripting

Why Shell Scripting?

  • When administering servers, you need to execute tons of commands
    • useradd dip
    • groupadd devops
    • mkdir temp
    • touch 1.txt
    • chmod 750 /temp
    • sudo apt docker
    • docker run ...
  • Instead of executing the command one by one, you can save the commands in a file and execute that file.
  • Such file is called a shell script.
  • File extension is .sh
  • Automate all your work:
    • Backup scripts -> Monitoring scripts -> Server Configuration scripts
  • Avoid repetitive work
  • Keep history of configuration
  • Share the instructions
  • Logic & Bulk Operations

How to execute Shell Scripts?

Shell

  • The program that interprets and executes the various commands that we type in the terminal
  • Translates our command that the OS Kernel can understand

Different Shell implementations

  • sh

    • Bourne Shell - /bin/sh
  • Bash

    • Bourne again shell - /bin/bash
    • Improved version of sh
    • Default shell program for most UNIX like systems
    • Bash is a shell program and a programming language
  • Shell and Bash terms are often used interchangeable

  • All shell script files have the same .sh file extension

How OS knows which shell to use?

  • We need to tell the OS
  • SH - #!/bin/sh
  • BASH - #!/bin/bash
  • ZSH - #!/bin/zsh

This is called "shebang" because of the first 2 characters "#!"

  • # = in musical notation, also called "sharp"
  • ! = also called "bang"
  • Shebang became a shortening of sharp-bang

Make shell script executable

  • To execute a shell script, you need to make it executable first, by adding executing permission
sudo chmod u+x first.sh # execute permission to user(owner)
sudo chmod g+x first.sh # execute permission to group
sudo chmod o+x first.sh # execute permission to other

Writing Shell Scripts

Variables

  • Used to store data and can be referenced later
  • Similar to variables in general programminglanguages
  • Store output of a command in a variable: variable_name=$(command)

Conditionals

  • Allow you to alter the control flow of the program
  • E.g. execute a command only when a certain condition is true
    if [ condition ]
    then
      statement
    elif [ condition ]
    then
      statement
    else
      statement
    fi

[ ... ] builtin command

  • Square brackets enclose expressions
  • It's a shorthand notation for the "test" command
    • if test -d "config" is the same

Boolean

  • A datatype that can only have 2 values:
    • True
    • False
  • Bash does have Boolean expressions in terms of comparison and conditions

File Test Operators

  • Test various properties associated with a file:
Operator Description Example
-b file Checks if file is a block special file; if yes, then the condition becomes true. [ -b $file ]
-c file Checks if file is a character special file; if yes, then the condition becomes true. [ -c $file ]
-d file Checks if file is a directory; if yes, then the condition becomes true. [ -d $file ]
-f file Checks if file is an ordinary file as opposed to a directory or special file; if yes, then the condition becomes true. [ -f $file ]
-g file Checks if file has its set group ID (SGID) bit set; if yes, then the condition becomes true. [ -g $file ]
-k file Checks if file has its sticky bit set; if yes, then the condition becomes true. [ -k $file ]
-p file Checks if file is a named pipe; if yes, then the condition becomes true. [ -p $file ]
-t file Checks if file descriptor is open and associated with a terminal; if yes, then the condition becomes true. [ -t $file ]
-u file Checks if file has its Set User ID (SUID) bit set; if yes, then the condition becomes true. [ -u $file ]
-r file Checks if file is readable; if yes, then the condition becomes true. [ -r $file ]
-w file Checks if file is writable; if yes, then the condition becomes true. [ -w $file ]
-x file Checks if file is executable; if yes, then the condition becomes true. [ -x $file ]
-s file Checks if file has size greater than 0; if yes, then condition becomes true. [ -s $file ]
-e file Checks if file exists; is true even if file is a directory but exists. [ -e $file ]

Relational Operators

  • Works only for numeric values
  • Assume variable a holds 10 and variable b holds 20 then:
Operator Description Example
-eq Checks if the value of two operands are equal or not; if yes, then the condition becomes true. [ $a -eq $b ] is not true
-ne Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true. [ $a -ne $b ] is true
-gt Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true. [ $a -gt $b ] is not true
-lt Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true. [ $a -lt $b ] is true
-ge Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true. [ $a -ge $b ] is not true
-le Checks if the value of left operand is less than or equal to the value of right operand; if yes, then the condition becomes true. [ $a -le $b ] is true

String Operators

  • Test strings for equality and more
  • Assume variable a holds "abc" and variable b holds "efg" then:
Operator Description Example
= Checks if the value of two operands are equal or not; if yes, then the condition becomes true [ $a = $b ] is not true
!= Checks if the value of two operands are equal or not; if values are not equal then the condition becomes true [ $a != $b ] is true
-z Checks if the given string operand size is zero; if it is zero length, then it returns true [ -z $a ] is not true
-n Checks if the given string operand size is non-zero; if it is nonzero length, then it returns true [ -n $a ] is not false
str Checks if str is not the empty string; if it is empty, then it returns false [ $a ] is not false

Passing arguments to a script

  • You can pass arguments when executing a script
    read -p "Please enter your name: " user_name
    echo "You name is $username"
  • We can read these passed parameters using special variables

Positional Parameters

  • Arguments passed to script are processed in the same order in which they're sent
  • The indexing of arguments starts at 1: $1
  • $* = represent all the arguments as a single string
  • $# = Total number of arguments provided
  • $? - captures value returned by last command Loops
  • Enables you to execute a set of commands repeatedly
  • There are different types of loops:
    • while loop
    • for loop
    • until loop
    • select loop

For Loop

  • Operates on lists of items
  • Repeats a set of commands for every item in the list
for var in word1 word2 ...
do
  statement(s) to be executed for every word
done

# Example
for param in $*
do
  if [ -d "$param" ]
    then
      echo "directory $param exist"
  fi
  echo $param
done

While Loop

  • Executes a set of commands repeatedly until some condition is matched
while condition
do
  statement(s) to be executed if command is true
done

# Example
count=0
while [ "$count" -lt "$#" ]
do
  echo "count: $count"
  count=$((count+1))
done

Functions

  • Enables you to break down the overall functionality of a script into smaller, logical code blocks
  • This code block can then be referenced ("called") anywhere in the script multiple times
  • You can accept parameters in a function
  • The parameters passed in are represented by $1, $2, etc.
function iterate {
  count=0
  while [ "$count" -lt 5 ]
  do
    echo "count: $count"
    count=$((count+1))
  done
}
iterate

Function Paramaters

function create_file() {
  filename=$1
  touch $filename
  echo "$filename created."
}

create_file hello.txt
create_file bye.sh
function sum() {
  total=$(($1+$2))
  return $total
}

sum 2 10
result=$?
echo "Result: $result"