Skip to main content

Shell Script

A shell is a program that interprets commands and acts as an interface between application layer and kernel of OS A Linux shell is command interpreter that interprets a user command which are directly entered by user or which can be read from a file called as shell programming or shell.

You can get the name of your shell prompt, with following command :

Shell Scripts

Syntax: #echo $SHELL Output: /bin/bash  When a group of commands has to execute regularly, it isbetter to store in a file. All such files are called shell scripts, shell program, or shell The extension is .sh is used for shell program
scripting.
You can get the name of your shell prompt, with followingprocedures.

Steps to create shell scripts

1. Open the terminal. Go to the directory where you want tocreate your script.
2. Create a file using vi editor(or any other editor). Name thescript file with extension .sh
3. To run your script in a certain shell, start your script with #!followed by the shell name. The sign #! is called she-bangand is written at top of the script. E.g. #! /bin/bash
4. Write some code
5. Save the script file as filename.sh 6. Make the script executable with command #chmod +x <fileName>
6. 7. Run the script using ./<fileName>
7. followed by the shell name. The sign #! is called she-bang
#chmod +x first.sh
First Shell Script
Output: Hello World
#vi first.sh
#! /bin/bash
echo “Hello World”
echo “Writing Shell Script is very easy!!!”
#./first.sh
Writing Shell Script is very easy!!!

Shell Scripting Variables

Scripts can contain variables inside the script.
A variable is a character string to which we assign a value. The value assigned could be anumber, text, filename etc Variable Names:
The name of a variable can contain only letters (a to z or A to Z), numbers ( 0 to 9) or theunderscore character ( _). By convention, Unix shell variables will have their names in UPPERCASE.

The following examples are valid variable names −
Following are the examples of invalid variable names − 2_VAR, -VARIABLE, VAR1-VAR2, VAR_A!

Defining Variables

Variables are defined as variable_name=variable_value . For example  NAME=“Nilesh "The above example defines the variable NAME and assigns the value“Nilesh" to it. Variables of this type are called scalar variables. A scalar variable can hold only one value ata time. Shell enables you to store any value you want in a variable. For example − VAR1=“Pune" VAR2=100
_ABC, TOKEN_A, VAR_1, VAR_2
_ABC, TOKEN_A, VAR_1, VAR_2

Accessing Values

To access the value stored in a variable, prefix its name with the dollar sign ($) −For example, the following script will access the value of defined variable NAMEand print it on STDOUT − echo $NAME

Read-only Variables

Shell provides a way to mark variables as read-only by using the read-onlycommand. After a variable is marked read-only, its value cannot be changed. For example, the following script generates an error while trying to change the valueof NAME − readonly NAME The above script will generate the following result − /bin/sh: NAME: This variable is read only.
#!/bin/sh
NAME=“Nilesh"
Shell provides a way to mark variables as read-only by using the read-only
#!/bin/sh
NAME=“Nilesh"
NAME=“Patil“

Unsetting Variables

Unsetting or deleting a variable directs the shell to remove the variable from the listof variables that it tracks. Once you unset a variable, you cannot access the stored value in the variable.  Following is the syntax to unset a defined variable using the unset command −unset variable_name You cannot use the unset command to unset variables that are marked readonly. Linux - Special Variables: The following table shows a number of special variables that you canuseinyourshell scripts 1. $0-The filename of the current script.
2. $n -These variables correspond to the arguments with which a script was invoked.Here n is a positive decimal number corresponding to the position of an argument(the first argument is $1, the second argument is $2, and so on). 3. $#- The number of arguments supplied to a script.
4. $?- The exit status of the last command executed.
The following table shows a number of special variables that you can use in your 
Command-Line Arguments:
The command-line arguments $1, $2, $3, ...$9 are positional parameters,with $0 pointing to the actual command, program, shell script, or functionand $1, $2, $3, ...$9 as the arguments to the command.  Following script uses various special variables related to the command lineecho "File Name: $0"
echo "First Parameter : $1"
echo "Total Number of Parameters : $#“  Here is a sample run for the above script − #./cmd_arg.sh 10 20
File Name : ./cmd_arg
First Parameter : 10
Second Parameter : 20
Total Number of Parameters : 2
#!/bin/sh
echo "Second Parameter : $2“
echo "Second Parameter : $2“

Exit Status

The $? variable represents the exit status of the previous Exit status is a numerical value returned by everycommand upon its completion.  As a rule, most commands return an exit status of 0if theywere successful, and 1 if they were unsuccessful.  Eg. #ls
#echo $? Will print 0
#cd Yogsh (Worng Dir name)
#echo $? Will print 1
command.
As a rule, most commands return an exit status of 0if they
Following are various operators supported by each shell.

Arithmetic Operators

+ (Addition)- Adds values.

- (Subtraction)- Subtracts right hand operand from left hand.

* (Multiplication)- Multiplies values on either side of the operator.
 
/ (Division)- Divides left hand operand by right hand operand.

% (Modulus)- Divides left hand operand by right hand operand and returnsremainder
Shell didn't originally have any mechanism to performsimple arithmeticoperations but it uses external programs, either awk or expr.

The following example shows how to add two numbers −
Shell Operators
val=`expr 2 + 2`
echo "Total value : $val”
The following points need to be considered 1. There must be spaces between operators and expressions. For example, 2+2 isnot correct; it should be written as 2 + 2.

2. The complete expression should be enclosed between ` ` called the backtick. Shell didn't originally have any mechanism to performsimple arithmetic

Relational Operators

Shell supports the following relational operators that are specific to numeric values.These operators do not work for string values unless their value is numeric. For example, following operators will work to check a relation between 10 and 20 aswell as in between "10" and "20" but not in between "ten" and "twenty". 1. -eq: Checks if the value of two operands are equal or not; if yes, then the conditionbecomes true. 2. -ne: Checks if the value of two operands are equal or not; if values are not equal,then the condition becomes true.

-gt: Checks if the value of left operand is greater than the value of right operand; ifyes, then the condition becomes true. 4.

-lt: Checks if the value of left operand is less than the value of right operand; if yes,then the condition becomes true.

-ge: Checks if the value of left operand is greater than or equal to the value of rightoperand; if yes, then the condition becomes true. 6.

-le: Checks if the value of left operand is less than or equal to the value of rightoperand; if yes, then the condition becomes true. It is very important to understand that all the conditional expressions should beplaced inside square braces with spaces around them. For example, [ $a <= $b ] is correct whereas, [$a <= $b] is incorrect.

Boolean Operators

The following Boolean operators are supported by theBourne Shell. Assume variable a holds 10 and variable b holds 20 then1.

! :- This is logical negation. This inverts a true conditioninto false and vice versa.
e.g. [ ! false ] is true.

-o :- This is logical OR. If one of the operands is true, thenthe condition becomes true. e.g. [ $a -lt 20 -o $b -gt 100 ] is true.

-a :-This is logical AND. If both the operands are true, thenthe condition becomes true otherwise false. e.g. [ $a -lt 20 -a $b -gt 100 ] is false.

File Test Operators

We have a few operators that can be used to test various properties associated with aUnix file. Assume a variable file holds an existing file name "test" the size of which is 100bytes and has read, write and execute permission on

-b file :-Checks if file is a block special file; if yes, then the condition becomes true.E.g. [ -b $file ] is false.

-c file :-Checks if file is a character special file; if yes, then the condition becomestrue. E.g.[ -c $file ] is false.

-d file :-Checks if file is a directory; if yes, then the condition becomes true. E.g.[-d$file ] is not true.

-f file :-Checks if file is an ordinary file as opposed to a directory or special file; ifyes, then the condition becomes true. E.g. [ -f $file ] is true.

-r file :-Checks if file is readable; if yes, then the condition becomes true. E.g. [ -r$file ] is true.

-w file :-Checks if file is writable; if yes, then the condition becomes true. E.g. [ -w$file ] is true.

-x file :-Checks if file is executable; if yes, then the condition becomes true. E.g. [ -x$file ] is true.

-s file :-Checks if file has size greater than 0; if yes, then condition becomes true.E.g. [ -s $file ] is true.

-d file :-Checks if file is a directory; if yes, then the condition becomes true. E.g.[-d]
Unix Shell supports conditional statements which are usedto perform different actions based on different conditions. We will now understand two decision-making statements

The if...else statements

If else statements are useful decision-making statements whichcan be used to select an option from a given set of options.
Shell Scripting if then else Unix Shell supports following forms of if…else statement −
if...fi statement
if...else...fi statement
here
if...elif...else...fi statement
The if...else statement
The case...esac statement

case Statement Syntax

The Bash case statement takes the following form:
case EXPRESSION in
The case statment
PATTERN_1)
STATEMENTS
;
PATTERN_2)
STATEMENTS

STATEMENTS ;
PATTERN_N) STATEMENTS ;
)
STATEMENTS ;
esac
The while loop enables you to execute a set of commandsrepeatedly until some condition occurs. It is usually used when you need to manipulate the value ofa variable repeatedly. The While loop

do Statement(s) to be executed if command is true

Syntax:
while command
while command
done

The while loop is perfect for a situation where you need toexecute a set of commands while some condition is true. Sometimes you need to execute a set of commands until acondition is true. The Untill Loop
doStatement(s) to be executed until command is true If the resulting value is false, given statement(s) are executed.  If the command is true then no statement will be executed andthe program jumps to the next line after the done statement.
Syntax:
until [command]
until [command]
done 

for (( Initialization; condition; updation )) 
The for Loop
Syntax of for like C programming language:
do
Statements;
done

Example:
f0or (( i=0; i<=5; i++) do
echo $i
done

SORT command is used to sort a file, arranging the records in aparticular order.  SORT command sorts the contents of a text file, line by line. sort is a standard command line program that prints the lines ofits input or concatenation of all files listed in its argument list insorted order.

The sort command is a command line utility for sortinglinesoftext files. It supports sorting alphabetically, in reverse order, bynumber, by month and can also remove duplicates.

SORT command in Linux The sort command can also sort by items not at the beginning ofthe line, ignore case sensitivity and return whether a file issorted or not. Sorting is done based on one or more sort keysextracted from each line of input.
By default, the entire input is taken as sort key. Blank space isthe default field separator. The sort command is a command line utility for sortinglinesof

# sort abc.txt

This command does not actually change the input file, i.e. stud.txt but displays thecontent of file in ascending order. 2. -o Option : Unix also provides us with special facilities like if you want to writethe output to a new file, output.txt, redirects the output like this or you can also usethe built-in sort option -o, which allows you to specify an output file.

syntax: #sort inputfile.txt > filename.txt
#sort -o filename.txt inputfile.txt

-r Option Sorting In Reverse Order


You can perform a reverse-order sort usingthe -r flag. the -r flag is an option of the sort command which sorts the input fileinExamples of sort commands
the -r flag. the -r flag is an option of the sort command which sorts the input fileinreverse order i.e. descending order by default. 4. -n Option: This option is used to sort the file with numeric data present inside. E.g.# sort -n filename.txt 5. -nr option : To sort a file with numeric data in reverse order we can use thecombination of two options as stated below.  E.g. # sort -nr filename.txt

-k Option

Unix provides the feature of sorting a table on the basis of any columnnumber by using -k option. Use the -k option to sort on a certain column. For example, use “-k 2” to sort on thesecond column. #sort –k colum number filename.txt

The cut command in UNIX is a command for cutting out the sections fromeach line of files and writing the result to standard output. It can be used to cut parts of a line by byte position, character and field.  Basically the cut command slices a line and extracts the text. It is necessary to specify option with command otherwise it gives error. Letus consider a file having name state.txt which contains 5 names of theIndian states. $ cat state.txt

Arunachal Pradesh
cut command in Linux Examples of cut commands:
# cut –b 1,2,3 state.txt
# cut -b 1-3,5-7 state.txt (Range of bytes can also be specified using thehyphen(-) )
Andhra Pradesh
Andhra Pradesh
Assam
Bihar
Chhattisgarh

It uses a special form for selecting bytes from beginning uptothe end of the line: 3. $ cut -b 1- state.txt In this, 1- indicate from 1st byte to end byte of a line4. $ cut -b -3 state.txt
$ cut -c 1-7 state.txt
Above cut command prints second, fifth and seventhcharacter from each line of the file. cut -c 1-7 state.txt
Above cut command prints first seven characters of eachline from the file.
In this, -3 indicate from 1st byte to 3rd byte of a line In this, -3 indicate from 1st byte to 3rd byte of a line

It is used to join files horizontally (parallel merging) by outputting linesconsisting of lines from each file specified, separated by tab as delimiter, to thestandard output.  Let us consider three files having name state, capital and number.  state and capital file contains 5 names of the Indian states and capitalsrespectively. number file contains 5 numbers.
Paste command in Linux

Filters are programs that take plain as standard input, transformsit into a meaningful format, and then returns it as standard Linux has a number of filters.

Some of the most commonly used filters are explained below

head : Displays the first n lines of the specified text files. If thenumber of lines is not specified then by default prints first 10
Filters in Linux
tail : It works the same way as head, just in reverse order. Theonly difference in tail is, it returns the lines from bottom to up.
output.
sort : Sorts the lines alphabetically by default but there aremany options available to modify the sorting mechanism.
cat : Displays the text of the file line by line.

uniq : Removes duplicate lines. uniq has a limitation that it canonly remove continuous duplicate lines(although this can befixed by the use of piping)  Syntax: # uniq [file path] #uniq /root/abc.txt  When applying uniq to sorted data, it removes the duplicatelines because, after sorting data, duplicate lines come together.

wc: wc command gives the number of lines, wordsandcharacters in the data.

grep : grep is used to search a particular information from a text8. tac : tac is just the reverse of cat and it works the same way, i.e.,instead of printing from lines 1 through n, it prints lines nthrough 1. It is just reverse of cat command. 9. nl : nl is used to number the lines of our text data Syntax: #nl [File Path]

#nl /root/abc.txt
wc: wc command gives the number of lines, words and file.

Menu card just for you !

Select Your favourite topic to learn.

Comments

Trending⚡

Understanding link.click() in JavaScript

Hey! Today i am going to share with you how to use link.click() function in javascript As a JavaScript developer, you may come across the need to programmatically click a link on a web page. The link.click() method is a commonly used way to do this, and it is important to understand how it works and when to use it. What is link.click()? link.click() is a method that can be used to simulate a click on a link element in JavaScript. It is typically used when you want to trigger a link click event programmatically, rather than requiring the user to physically click the link. How to use link.click() Using link.click() is relatively straightforward. First, you need to select the link element you want to click using a DOM selector such as getElementById() or querySelector(). Then, you can call the click() method on the link element to simulate a click. Here is an example: // select the link element const myLink = document.getElementById('my-link'); // simulate a cl...

How to Create Studio Ghibli-Style AI Images on ChatGPT for Free

How to Create Studio Ghibli-Style AI Images on ChatGPT for Free AI-generated art is making waves across the internet, captivating audiences with stunning, ethereal visuals inspired by the iconic animation style of Studio Ghibli . These AI-crafted images, from dreamy landscapes to expressive characters, reflect the timeless magic of Hayao Miyazaki ’s beloved films such as Spirited Away , My Neighbor Totoro , and Howl’s Moving Castle . Thanks to recent advancements in AI technology, particularly OpenAI ’s latest ChatGPT update, users can now create their own Studio Ghibli-inspired illustrations effortlessly by entering simple text prompts. This exciting feature is transforming digital art creation and making it accessible to both professionals and beginners. In this article, we’ll guide you through creating Ghibli-style AI images using ChatGPT and explore free alternatives for users who don’t yet have access to this feature. Ghibli AI generator free Step-by-Step Guide: How to Crea...

Value Model vs Reference Model

Value Model vs Reference Model In programming languages, two different models are used for variables.  These are:  Value Model  A variable contains a value. The name of the variable gives its value.  Reference Model A variable contains (say y) refers to another variable (say x) with a value. The variable ‘y’ is used to access the value of ‘x’ indirectly.  The ‘C’ language is based on value model. However, by using pointers, we can implement the reference model. The pointer is used to access the value of a variable indirectly. Also Read Static and Dynamic Memory Allocation Memory Leak and Dangling Pointer Memory Allocation for 2D Array Dynamic Memory Allocation Pointer Constant and Constant Pointer Pointer Declarations and their Meanings Functions and Pointers Initializing Pointer to Pointer Pointer to Pointer Multiple Indirection Relationship between Array and Pointer Pointer to Array Pointer Arithmetic Types of Pointer Illustrat...

How to write programs in Bhai language

Bhai Language Bhai language is fun Programming language , with this language you can makes jokes in hindi. Bhai language written in typescript. It's very funny , easy and amazing language. Keywords of this language written in Hindi . Starting and ending of the program Start program with keyword " hi bhai " and end with " bye bhai ". It's compulsory to add this keyword before starting and end on the program. You write your programming logic inside this hi bhai and bye bhai . How to declare variables in Bhai language We use " bhai ye hai variable_name" keyword for declaring variables. In javascript we use var keyword for declaring variables but here you have to use " bhai ye hai " keyword. If you are declaring string then use " " double quotes. You can use Boolean variable like sahi and galat for true and false . How to print output in Bhai language You have to use " bol bhai " keyword for ...

ChatGPT Now Allows Free Users to Create Ghibli-Style AI Images – Here’s How

OpenAI has finally expanded its native image generation feature to free ChatGPT users, allowing them to transform images into stunning Studio Ghibli-style artwork . While the company has yet to make an official announcement, multiple tests using free ChatGPT accounts confirm that the feature is now accessible without requiring a paid subscription. Ghibli AI Images Now Available for Free Users Previously, OpenAI restricted its image generation capabilities to ChatGPT Plus, Pro, and Team users. This led free-tier users to seek alternatives like xAI’s Grok and Google’s Gemini . However, these tools often lacked the same level of detail and artistic refinement as OpenAI’s model. Now, with the rollout extending to free users, everyone can experience the magic of Ghibli-style AI transformations. How to Create Ghibli-Style AI Images with ChatGPT If you want to turn your photos into Ghibli-inspired masterpieces, follow these simple steps: Visit ChatGPT – Open the ChatGPT website or...

Quiz tells you what type of wife you want

What Type of Wife are You Looking For? Attend this quiz and know your wife expections Quiz reveals type of wife you expect, lets answer carefully... Personality Questions: 1. What type of personality are you looking for in a wife? Quiet and reserved Outgoing and social Intelligent and witty 2. What type of sense of humor are you looking for in a wife? Dry and sarcastic Witty and clever Playful and silly 3. What type of interests are you looking for in a wife? Intellectual and educational Creative and artistic Athletic and outdoorsy Values Questions: 4. What type of family values are you looking for in a wife? Traditional and conservative Open-minded and progressive Balanced and equal 5. What type of political views...