Shell Script

Shell Script

-> Writing a code line by line and executing top to bottom. And, it is denoted with .sh.

-> In the first line of the shell script always write the first "chebang" or a "bang" and it starts with a number sign and an exclamation mark(#!) followed by the interpreter such as /bin/bash.

-> #!: It tells which shell we are using.

-> Shell types:

a)BASH

b)CSHELL

c)ZSH

So, the first line always starts with #! /bin/bash. It means your script has been started.

To write a script, we can use a text editor and there are many text editors available. For eg. vi or vim is the command line interface text editor, gedit is the GUI editor.

Eg: To write the first script

  1. vim myFirstScript.sh: the vim editor will open and now you can write your first script.

  2. cat myFirstScript.sh: to see the content of the script.

  3. Your script should be executable, if not, then give the executable permission.

To check executable/not : ls -la myFirstScript.sh

To modify permission: chmod <<permission>> <<filename>> eg: chmod 770 myFirstScript.sh

7 - user (Read + Write + Execute)

7 - group(Read + Write + Execute)

0 - others( no permission)

To execute the script: ./myFirstScript.sh

How to create a folder and file through the script?

Note: Linux is case-sensitive, so the file names, variables, and arrays used in shell scripts are also case-sensitive.

for eg: name="vinay" echo "My name is $name"

File Naming Conventions:

  1. The file name can be max. of 255 characters.

  2. The name may contain alphabets, digits, dots and underscores.

  3. System commands or Linux reserve keywords can not be used for file names.

  4. The file system is case-sensitive.

    eg: hello.sh, Hello.sh, Hello_123.sh, hello95.sh

Comments:

A comment is used to give information about your code that is not executable. Single-line comments can be done using #. And, For multiline comments, we can use the below example.

<<COMMENT1 your comment 1 comment 2 ............. COMMENT1

Variables:

The variable is used to store any data. There are two types of variables in the Linux shell script. 1. System variables 2. User-defined variables

Variable naming conventions

-> Variable name must start with an alphanumeric character or underscore character. -> Environment/system variables (PAGE, EDITOR, SHELL, BASH_VERSION etc.) are capitalized. All other variable names should be in lowercase. -> To see all variables on the terminal, use the command: env or printenv. -> User-defined variables created and maintained by users. It can be defined using any valid variable name, but it's a good practice to avoid all uppercase names. ex: firstName= "Vinay"

Command Line Arguments

-> During shell script execution, values can be passed through a command prompt called Command Line Arguments.

-> We can specify n number of arguments, there is no limitation.

-> Each argument is separated by space.

Diff b/w '$*' and '$@'

$*: * treated as one text string. $@: @ treated as a separate string.

How to take input from users?

read: using the "read" command we can take the input from the user at runtime.

Conditional Commands

If-else condition

Syntax: if[ condition ] then commands inside if else commands inside else fi

Note: if and then must be separated either with a new line or a semicolon(;). fi -> it is the termination statement.

if [ $# -lt 2 ]
then 
    echo "command line arguments are missing"
elif [ $1 -eq $2 ]&&[ $2 -eq $3 ]
then
    echo "All the three are equal"
elif [ $1 -eq $2 ]||[ $1 -eq $3 ]
then
    echo "I cannot figure out which number is biggest"
elif [ $1 -gt $2 ]
then
    if [ $1 -gt $3 ]
    then
        echo "$1 is biggest number"
    else
        echo "$3 is biggest number"
    fi
elif [ $2 -gt $3 ]
then
    echo "$2 is biggest number"
else
    echo

 "$3 is biggest number"
fi

OR

Write a script to check file exists or not.

Loop: for-loop

Syntax: for (condition) do write your command here until the condition is not satisfied. done

How to print all the files present in /home/ubuntu through for loop?

while loop

Syntax: while [ condition ] do command1 command2 ...................................................... done

Switch Case:

It is used when a decision has to be made against multiple choices. In other words, it is useful when an expression can have multiple values.

Syntax:

case EXPRESSION in Pattern_Case_1) STATEMENTS ;; Pattern_Case_1) STATEMENTS ;; Pattern_Case_N) STATEMENTS ;; *) STATEMENTS ;; esac

  • A case statement begins with the case keyword which is followed by an expression and the in the keyword.

  • It ends with the exact keyword.

  • Multiple pattern cases can be used separated by the | operator.

  • The closing parenthesis operator ‘)’ is used to end the pattern cases list.

  • A pattern case can contain special characters.

  • A pattern case and its body are termed a clause.

  • Pattern case body must be followed by ;;.

  • In case an expression matches with two pattern cases then in such case the body corresponding to the first matching pattern case that matches the expression is executed.

  • Like C provides a default keyword for the default statement, likewise in the Bash case statement, we can use the wildcard asterisk symbol (*) and define a final pattern case to define the default case.

  • In case no pattern is matched, the return status is zero. Otherwise, the return status is the exit status of the executed body of the matched pattern case.

Task 1: Write a bash script when the script is executed with 3 arguments(one is a directory name, the second is the start number and the third is the end number of directories). It creates a specified number of directories with a dynamic directory name.

Example: When the script is executed as, ./createDirectories.sh day 1 90, then it creates 90 directories as day1 day2 day3 ...................day90

Output:

Task 2: Create a script to back up all your work done till now.

We can use Cron and Crontab to take a backup of the script.

Cron: Cron is a service/utility which allows the scheduling/automation of the task at a particular period.

Crontab: The crontab is a list of commands that you want to run on a regular schedule, and also the name of the command used to manage that list. Crontab stands for “cron table, ” because it uses the job scheduler cron to execute tasks

Crontab is a file that contains a set of commands.

The above script is written for checking the disk. It will print a CRITICAL message for a file with the date and time when the usage of the disk will be greater than the alert which is initialized at 30.

Output:

Now, we can schedule the above script with the help of Crontab to take the backup/check the CRITICAL file every day or once a month.

Schedule a cron to execute the above scripts at 2 am daily and take a backup inside any file.

Thank you for reading this Blog. Hope you learned something new today! If you found this blog helpful, please share it with others.