Basics of Shell Script


This blog explains the basics of shell scripting for users of Linux or Unix operating systems.

What is shell script?

Shell script is basically a computer program which divided into two part SHELL & SCRIPT.
• Shell is an Interpreter which converts low level & high level language in to machine language for Unix based Operating systems .
• Script stands for Set of Commands.

What Types of shell are Supported Shell in Linux ?

Below (snapshot) are the few examples of shells supported by Linux 6. It may vary from version to version

How to write as a shell script ?

#!/bin/bash – This is known as header or shebang of a script.
• #! - Is a symbol which is called the interpreter.

• #Commented line – Only readable format shows what script is executing /bin/bash is the location of shell & shell we are using is bash .

For example.

Here we have created a script in bash shell & executed using sh.

What are variables in shell scripting ?

Variables store any values which can be called during the execution of a script.

What are the Types of variables ? There are two types of variables.

• System defined Variable (SDV) - These are predefined & maintained by Linux only. SDV will always show in Capital letters

• User defined Variable (UDV) – These can be created & maintained by user. UDV should always define in Small letters

What are special variables ?

• $0 - Check current script name

• $n - Sequence of arguments

• $# - To check count (number of arguments) in script.

• $* - It stores complete set of positional parameter in a single string

• $@ - Quoted string treated as separate arguments.

• $? - exit status of command

• $$ - Check PID of current shell.

• $! - check PID of last background Job

Below is an example.

Output:

Arithmetic Operators -

These operators are used for arithmetic calculations .

Below is an example:

Output:

Functions and Arguments –

A function is a group of commands which can be used as a single handle. To execute this set of commands, call the function by the name provided.

Below is an example of single function. We have created a shell script using a single function & called the function in script at very last.

Output

Below is an example of two functions.

Below we have created shell script calling two different functions. Output of script depends upon the calling sequence of functions.

Output:

Conclusion –

Shell scripting can be used to automate manual tasks. It is very useful for most repetitive tasks which are time consuming to execute or schedule using one line at a time

Let our experts guide you on your cloud-native journey.

Use the Feedback tab to make any comments or ask questions. You can also start a conversation with us.

post avatar
Love Uniyal

Share this information: