0% found this document useful (0 votes)
41 views

LINUX SHELL PROGRAMMING LAB

Uploaded by

nkk285701
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views

LINUX SHELL PROGRAMMING LAB

Uploaded by

nkk285701
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

LINUX SHELL PROGRAMMING LAB

1. Use of Basic Unix Shell Commands: ls, mkdir, rmdir, cd, cat,
banner, touch, file, wc, sort, cut, grep, dd, dfspace, du, ulimit.

Ans:-

 ls: Lists files and directories in the current directory.

Example: ls -l (lists files and directories in long format)


 mkdir: Creates a new directory.

Example: mkdir mydir (creates a directory named "mydir")


 rmdir: Removes an empty directory.

Example: rmdir mydir (removes the directory named "mydir")


 cd: Changes the current directory.

Example: cd mydir (changes the current directory to "mydir")


 cat: Concatenates and displays the contents of a file.

Example: cat myfile.txt (displays the contents of "myfile.txt")


 banner: Prints large letters in a banner format.

Example: banner Hello (prints the word "Hello" in a banner


format)
 touch: Creates an empty file or updates the timestamp of an
existing file.

Example: touch myfile.txt (creates an empty file named


"myfile.txt")
 file: Determines the file type.

Example: file myfile.txt (displays the file type of "myfile.txt")


 wc: Counts the number of lines, words, and characters in a file.

Example: wc myfile.txt (displays the line count, word count, and


character count of "myfile.txt")
 sort: Sorts the lines of a file in ascending order.

Example: sort myfile.txt (sorts the lines of "myfile.txt" in


ascending order)
 cut: Extracts specific columns or fields from a file.

Example: cut -d"," -f1 myfile.csv (extracts the first field from a
comma-separated file)
 grep: Searches for a pattern in files.

Example: grep "hello" myfile.txt (searches for the word "hello" in


"myfile.txt")
 dd: Copies and converts files.

Example: dd if=inputfile of=outputfile bs=blocksize (copies the


content of "inputfile" to "outputfile" using a specific block size)
 df: Displays disk space usage of file systems.

Example: df -h (displays disk space usage in a human-readable


format)
 du: Estimates file and directory space usage.

Example: du -sh mydir (displays the total space used by "mydir"


in a human-readable format)
 ulimit: Sets or displays user resource limits.

Example: ulimit -n (displays the maximum number of open file


descriptors for the current shell session)

2. Commands related to inode, I/O redirection and piping, process


control commands, mails.

Ans:-

 ls -i: Displays the inode number along with the file or directory
names.

Example: ls -i myfile.txt (displays the inode number of


"myfile.txt")
 find: Searches for files and directories based on various criteria,
including inode.

Example: find /path/to/directory -inum <inode_number> (finds


the file or directory with the specified inode number)
 I/O Redirection:

 >: Redirects standard output to a file, overwriting its contents.


Example: ls > file.txt (redirects the output of ls command to a file
named "file.txt")
 >>: Redirects standard output to a file, appending to its contents.
Example: echo "Hello" >> file.txt (appends "Hello" to the end of
the file "file.txt")
 <: Redirects standard input from a file.
Example: sort < myfile.txt (sorts the contents of "myfile.txt")
 Piping:
 |: Sends the output of one command as the input to another
command.
Example: ls -l | grep ".txt" (lists all the files in the current
directory with the ".txt" extension)
 Process Control Commands:

 ps: Displays information about active processes.


Example: ps -ef (displays information about all running
processes)
 kill: Sends a signal to terminate a process.
Example: kill <process_id> (sends a termination signal to the
process with the specified ID)
 top: Displays real-time information about system processes.
Example: top (displays an updated list of active processes and
system resource usage)
 Mail Commands:

 mail: Sends and receives emails from the command line.


Example: mail -s "Subject" [email protected] < message.txt
(sends an email with a subject and content from a file)
 mailq: Displays the mail queue.
Example: mailq (displays a list of emails waiting in the mail
queue)
 newaliases: Rebuilds the mail aliases database.
Example: newaliases (updates the mail aliases database with
changes made to the aliases file)

3. Shell Programming: Shell script based on control structure- If-then-


fi, if-then-else-if, nested if-else, to find:
3.1 Greatest among three numbers.
3.2 To find a year is leap year or not.
3.3 To input angles of a triangle and find out whether it is valid
triangle or not.
3.4 To check whether a character is alphabet, digit or special
character.
3.5 To calculate profit or loss.

Code:-

#!/bin/bash

# 3.1 Greatest among three numbers


echo "Enter three numbers: "
read num1 num2 num3

if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]; then


echo "$num1 is the greatest number."
elif [ $num2 -gt $num1 ] && [ $num2 -gt $num3 ]; then
echo "$num2 is the greatest number."
else
echo "$num3 is the greatest number."
fi

# 3.2 To find a year is leap year or not


echo "Enter a year: "
read year

if [ $((year % 4)) -eq 0 ] && [ $((year % 100)) -ne 0 ] || [ $((year %


400)) -eq 0 ]; then
echo "$year is a leap year."
else
echo "$year is not a leap year."
fi

# 3.3 To input angles of a triangle and find out whether it is a valid


triangle or not
echo "Enter three angles of a triangle: "
read angle1 angle2 angle3

if [ $((angle1 + angle2 + angle3)) -eq 180 ]; then


echo "It is a valid triangle."
else
echo "It is not a valid triangle."
fi

# 3.4 To check whether a character is alphabet, digit, or special


character
echo "Enter a character: "
read char

if [[ $char == [[:alpha:]] ]]; then


echo "The character is an alphabet."
elif [[ $char == [[:digit:]] ]]; then
echo "The character is a digit."
else
echo "The character is a special character."
fi

# 3.5 To calculate profit or loss


echo "Enter the cost price: "
read cost_price
echo "Enter the selling price: "
read selling_price

if [ $selling_price -gt $cost_price ]; then


profit=$((selling_price - cost_price))
echo "Profit: $profit"
elif [ $cost_price -gt $selling_price ]; then
loss=$((cost_price - selling_price))
echo "Loss: $loss"
else
echo "No profit, no loss."
fi

Expected Output:-

Greatest among three numbers:

Enter three numbers:


Input: 5, 9, 3
Output: 9 is the greatest number.
To find a year is a leap year or not:

Enter a year:
Input: 2024
Output: 2024 is a leap year.
To input angles of a triangle and find out whether it is a valid triangle
or not:

Enter three angles of a triangle:


Input: 60, 70, 50
Output: It is a valid triangle.
To check whether a character is an alphabet, digit, or special
character:

Enter a character:
Input: A
Output: The character is an alphabet.
To calculate profit or loss:

Enter the cost price:


Input: 200
Enter the selling price:
Input: 300
Output: Profit: 100

4. Shell Programming - Looping- while, until, for loops


4.1 Write a shell script to print all even and odd number from 1 to
10.
4.2 Write a shell script to print table of a given number
4.3 Write a shell script to calculate factorial of a given number.
4.4 Write a shell script to print sum of all even numbers from 1 to
10.
4.5 Write a shell script to print sum of digit of any number.

Code:-

#!/bin/bash

# 4.1 Write a shell script to print all even and odd numbers from 1 to
10
echo "Even numbers:"
for ((i=1; i<=10; i++))
do
if [ $((i % 2)) -eq 0 ]; then
echo $i
fi
done

echo "Odd numbers:"


for ((i=1; i<=10; i++))
do
if [ $((i % 2)) -ne 0 ]; then
echo $i
fi
done

# 4.2 Write a shell script to print the table of a given number


echo "Enter a number:"
read number

echo "Table of $number:"


for ((i=1; i<=10; i++))
do
result=$((number * i))
echo "$number x $i = $result"
done

# 4.3 Write a shell script to calculate the factorial of a given number


echo "Enter a number:"
read number

factorial=1
counter=1
while [ $counter -le $number ]
do
factorial=$((factorial * counter))
counter=$((counter + 1))
done
echo "Factorial of $number is: $factorial"

# 4.4 Write a shell script to print the sum of all even numbers from 1
to 10
sum=0
for ((i=1; i<=10; i++))
do
if [ $((i % 2)) -eq 0 ]; then
sum=$((sum + i))
fi
done
echo "Sum of even numbers from 1 to 10: $sum"

# 4.5 Write a shell script to print the sum of digits of any number
echo "Enter a number:"
read number

sum=0
while [ $number -gt 0 ]
do
digit=$((number % 10))
sum=$((sum + digit))
number=$((number / 10))
done
echo "Sum of digits: $sum"

Expected Output:-
Write a shell script to print all even and odd numbers from 1 to 10:

Even numbers:
Output: 2 4 6 8 10
Odd numbers:
Output: 1 3 5 7 9
Write a shell script to print the table of a given number:

Enter a number:
Input: 5
Output:
Table of 5:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Write a shell script to calculate the factorial of a given number:

Enter a number:
Input: 4
Output: Factorial of 4 is: 24
Write a shell script to print the sum of all even numbers from 1 to 10:

Output: Sum of even numbers from 1 to 10: 30


Write a shell script to print the sum of digits of any number:

Enter a number:
Input: 12345
Output: Sum of digits: 15

5. Shell Programming - case structure, use of break

5.1 Write a shell script to make a basic calculator which performs


addition, subtraction, Multiplication, division
5.2 Write a shell script to print days of a week.
5.3 Write a shell script to print starting 4 months having 31 days.

Code:-

#!/bin/bash

# 5.1 Write a shell script to make a basic calculator


echo "Enter two numbers: "
read num1 num2

echo "Select operation:"


echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo "4. Division"
read choice

case $choice in
1)
result=$((num1 + num2))
echo "Addition: $num1 + $num2 = $result"
;;
2)
result=$((num1 - num2))
echo "Subtraction: $num1 - $num2 = $result"
;;
3)
result=$((num1 * num2))
echo "Multiplication: $num1 x $num2 = $result"
;;
4)
if [ $num2 -eq 0 ]; then
echo "Error: Division by zero not allowed."
else
result=$((num1 / num2))
echo "Division: $num1 / $num2 = $result"
fi
;;
*)
echo "Invalid choice!"
;;
esac

# 5.2 Write a shell script to print days of the week


echo "Enter a number (1-7): "
read day

case $day in
1)
echo "Sunday"
;;
2)
echo "Monday"
;;
3)
echo "Tuesday"
;;
4)
echo "Wednesday"
;;
5)
echo "Thursday"
;;
6)
echo "Friday"
;;
7)
echo "Saturday"
;;
*)
echo "Invalid number!"
;;
esac

# 5.3 Write a shell script to print starting 4 months having 31 days


echo "Starting 4 months with 31 days:"
counter=1
month=1

while [ $counter -le 4 ]


do
case $month in
1 | 3 | 5 | 7 | 8 | 10 | 12)
echo "Month $month: 31 days"
counter=$((counter + 1))
;;
*)
;;
esac

month=$((month + 1))
done

Expected Output:-
Write a shell script to make a basic calculator:

Enter two numbers:


Input: 10, 5
Select operation:
Input: 1 (Addition)
Output: Addition: 10 + 5 = 15
Write a shell script to print days of the week:

Enter a number (1-7):


Input: 3
Output: Tuesday
Write a shell script to print starting four months having 31 days:

Output: Starting 4 months with 31 days:


Month 1: 31 days
Month 3: 31 days
Month 5: 31 days
Month 7: 31 days
6. Shell Programming - Functions
6.1 Write a shell script to find a number is Armstrong or not.
6.2 Write a shell script to find a number is palindrome or not.
6.3 Write a shell script to print Fibonacci series.
6.4 Write a shell script to find prime number.
6.5 Write a shell script to convert binary to decimal and decimal
to binary

Code:-

#!/bin/bash

# 6.1 Write a shell script to find a number is Armstrong or not


isArmstrong() {
local number=$1
local sum=0
local temp=$number
local length=${#number}

while [ $temp -gt 0 ]


do
local digit=$((temp % 10))
sum=$((sum + digit**length))
temp=$((temp / 10))
done

if [ $sum -eq $number ]; then


echo "$number is an Armstrong number."
else
echo "$number is not an Armstrong number."
fi
}

# 6.2 Write a shell script to find a number is palindrome or not


isPalindrome() {
local number=$1
local reverse=""
local temp=$number

while [ $temp -gt 0 ]


do
local digit=$((temp % 10))
reverse="$reverse$digit"
temp=$((temp / 10))
done

if [ $reverse -eq $number ]; then


echo "$number is a palindrome number."
else
echo "$number is not a palindrome number."
fi
}

# 6.3 Write a shell script to print Fibonacci series


printFibonacci() {
local limit=$1
local num1=0
local num2=1

echo "Fibonacci series up to $limit:"


echo -n "$num1 $num2 "

while [ $num2 -lt $limit ]


do
local next=$((num1 + num2))
echo -n "$next "
num1=$num2
num2=$next
done

echo
}

# 6.4 Write a shell script to find prime numbers


isPrime() {
local number=$1
local flag=0

if [ $number -eq 1 ]; then


echo "1 is not a prime number."
else
for ((i=2; i <= number/2; i++))
do
if [ $((number % i)) -eq 0 ]; then
flag=1
break
fi
done

if [ $flag -eq 0 ]; then


echo "$number is a prime number."
else
echo "$number is not a prime number."
fi
fi
}
# 6.5 Write a shell script to convert binary to decimal and decimal to
binary
binaryToDecimal() {
local binary=$1
local decimal=0
local power=0

while [ $binary -ne 0 ]


do
local digit=$((binary % 10))
decimal=$((decimal + digit * 2**power))
power=$((power + 1))
binary=$((binary / 10))
done

echo "Decimal: $decimal"


}

decimalToBinary() {
local decimal=$1
local binary=""

while [ $decimal -ne 0 ]


do
local digit=$((decimal % 2))
binary="$digit$binary"
decimal=$((decimal / 2))
done

echo "Binary: $binary"


}

# Main program

# 6.1 Test Armstrong number


echo "Enter a number to check for Armstrong: "
read armstrongNumber
isArmstrong $armstrongNumber

# 6.2 Test Palindrome number


echo "Enter a number to check for Palindrome: "
read palindromeNumber
isPalindrome $palindromeNumber

# 6.3 Test Fibonacci series


echo "Enter a limit for Fibonacci series: "
read fibonacciLimit
printFibonacci $fibonacciLimit
# 6.4 Test Prime number
echo "Enter a number to check for Prime: "
read primeNumber
isPrime $primeNumber

# 6.5 Test Binary to Decimal and Decimal to Binary conversion


echo "Enter a binary number: "
read binaryNumber
binaryToDecimal $binaryNumber

echo "Enter a decimal number: "


read decimalNumber
decimalToBinary $decimalNumber

7. Write a shell script to print different shapes- Diamond, triangle,


square, rectangle, hollow square etc.

Code:-

#!/bin/bash

# Function to print a diamond shape


printDiamond() {
local n=$1
local spaces=$((n - 1))
local stars=1

for ((i=1; i<=n; i++))


do
for ((j=1; j<=spaces; j++))
do
echo -n " "
done

for ((j=1; j<=stars; j++))


do
echo -n "*"
done

echo
spaces=$((spaces - 1))
stars=$((stars + 2))
done

spaces=1
stars=$((stars - 2))
for ((i=1; i<=n-1; i++))
do
for ((j=1; j<=spaces; j++))
do
echo -n " "
done

for ((j=1; j<=stars; j++))


do
echo -n "*"
done

echo
spaces=$((spaces + 1))
stars=$((stars - 2))
done
}

# Function to print a triangle shape


printTriangle() {
local n=$1

for ((i=1; i<=n; i++))


do
for ((j=1; j<=n-i; j++))
do
echo -n " "
done

for ((j=1; j<=2*i-1; j++))


do
echo -n "*"
done

echo
done
}

# Function to print a square shape


printSquare() {
local n=$1

for ((i=1; i<=n; i++))


do
for ((j=1; j<=n; j++))
do
echo -n "*"
done
echo
done
}

# Function to print a rectangle shape


printRectangle() {
local rows=$1
local cols=$2

for ((i=1; i<=rows; i++))


do
for ((j=1; j<=cols; j++))
do
echo -n "*"
done

echo
done
}

# Function to print a hollow square shape


printHollowSquare() {
local n=$1

for ((i=1; i<=n; i++))


do
for ((j=1; j<=n; j++))
do
if [ $i -eq 1 ] || [ $i -eq $n ] || [ $j -eq 1 ] || [ $j -eq $n ]; then
echo -n "*"
else
echo -n " "
fi
done

echo
done
}

# Main program

echo "Select a shape to print:"


echo "1. Diamond"
echo "2. Triangle"
echo "3. Square"
echo "4. Rectangle"
echo "5. Hollow Square"
read choice
case $choice in
1)
echo "Enter the size of the diamond:"
read size
printDiamond $size
;;
2)
echo "Enter the size of the triangle:"
read size
printTriangle $size
;;
3)
echo "Enter the size of the square:"
read size
printSquare $size
;;
4)
echo "Enter the number of rows in the rectangle:"
read rows
echo "Enter the number of columns in the rectangle:"
read cols
printRectangle $rows $cols
;;
5)
echo "Enter the size of the hollow square:"
read size
printHollowSquare $size
;;
*)
echo "Invalid choice!"
;;
esac
8. Shell Programming – Arrays
8.1 Write a C program to read and print elements of array.
8.2 Write a C program to find sum of all array elements.
8.3 Write a C program to find reverse of an array.
8.4 Write a C program to search an element in an array.
8.5 Write a C program to sort array elements in ascending or
descending order.

Code:-

8.1 C program to read and print elements of an array:

#include <stdio.h>

int main() {
int arr[100], size, i;

printf("Enter the size of the array: ");


scanf("%d", &size);

printf("Enter array elements:\n");


for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

printf("Array elements are: ");


for (i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Expected Output:

Enter the size of the array: 5


Enter array elements:
10
20
30
40
50
Array elements are: 10 20 30 40 50
8.2
C program to find the sum of all array elements:

#include <stdio.h>

int main() {
int arr[100], size, i, sum = 0;

printf("Enter the size of the array: ");


scanf("%d", &size);

printf("Enter array elements:\n");


for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
sum += arr[i];
}

printf("Sum of array elements: %d\n", sum);

return 0;
}

Expected Output:

Enter the size of the array: 5


Enter array elements:
10
20
30
40
50
Sum of array elements: 150

8.3 C program to find the reverse of an array:

#include <stdio.h>

int main() {
int arr[100], size, i;

printf("Enter the size of the array: ");


scanf("%d", &size);

printf("Enter array elements:\n");


for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}
printf("Reverse of array: ");
for (i = size - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Expected Output:

Enter the size of the array: 5


Enter array elements:
10
20
30
40
50
Reverse of array: 50 40 30 20 10

8.4 C program to search for an element in an array:

#include <stdio.h>

int main() {
int arr[100], size, i, element, found = 0;

printf("Enter the size of the array: ");


scanf("%d", &size);

printf("Enter array elements:\n");


for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

printf("Enter the element to search: ");


scanf("%d", &element);

for (i = 0; i < size; i++) {


if (arr[i] == element) {
found = 1;
break;
}
}

if (found) {
printf("Element %d found at index %d\n", element, i);
} else {
printf("Element %d not found in the array\n", element);
}

return 0;
}

Expected Output:

mathematica
Copy code
Enter the size of the array: 5
Enter array elements:
10
20
30
40
50
Enter the element to search: 30
Element 30 found at index 2

8.5 C program to sort array elements in ascending or descending


order:
c
Copy code
#include <stdio.h>

void bubbleSort(int arr[], int size, int order) {


int i, j, temp;

for (i = 0; i < size - 1; i++) {


for (j = 0; j < size - i - 1; j++) {
if (order == 0) {
// Ascending order
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
} else {
// Descending order
if (arr[j] < arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}

int main() {
int arr[100], size, i, order;

printf("Enter the size of the array: ");


scanf("%d", &size);

printf("Enter array elements:\n");


for (i = 0; i < size; i++) {
scanf("%d", &arr[i]);
}

printf("Enter the sorting order (0 for ascending, 1 for descending): ");


scanf("%d", &order);

bubbleSort(arr, size, order);

if (order == 0) {
printf("Array elements in ascending order: ");
} else {
printf("Array elements in descending order: ");
}

for (i = 0; i < size; i++) {


printf("%d ", arr[i]);
}
printf("\n");

return 0;
}in ascending order: 10 20 30 40 50

Expected Output:-

Enter the size of the array: 5


Enter array elements:
10
30
20
50
40
Enter the sorting order (0 for ascending, 1 for descending): 0
Array elements in ascending order: 10 20 30 40 50
COURSE OUTCOMES

 Use of Basic Unix Shell Commands:

Familiarity with basic Unix shell commands for file and directory
manipulation.
Understanding of common shell commands such as ls, mkdir,
rmdir, cd, cat, touch, etc.
Ability to use commands like file, wc, sort, cut, grep for file
analysis and manipulation.
Knowledge of commands like dd, du, dfspace for disk
management and utilization.
Understanding of ulimit command for resource limitation.

 Commands related to inode, I/O redirection and piping, process


control commands, mails:

Understanding of inode and its significance in file systems.


Knowledge of I/O redirection techniques for input/output stream
manipulation.
Ability to use piping to connect the output of one command as
input to another.
Understanding of process control commands for managing and
monitoring processes.
Familiarity with sending and receiving emails using command-
line tools.

 Shell Programming: Shell script based on control structure:

Understanding of control structures in shell scripting (if-then-fi,


if-then-else-if, nested if-else).
Ability to write shell scripts to solve problems involving
conditional statements.
Familiarity with script execution and condition evaluation in shell
scripts.
Knowledge of arithmetic operations and comparison operators in
shell scripting.

 Shell Programming - Looping:

Understanding of looping constructs in shell scripting (while,


until, for loops).
Ability to write shell scripts to perform repetitive tasks using
loops.
Knowledge of loop control statements like break and continue.
Familiarity with loop termination conditions and loop variables.

 Shell Programming - case structure, use of break:

Understanding of case structure in shell scripting for multiple


conditional branches.
Ability to write shell scripts using case structure to perform
different actions based on input.
Knowledge of using break to exit from a loop or switch case
statement.
Familiarity with handling multiple cases and default case in
switch case statement.

 Shell Programming - Functions:

Understanding of functions in shell scripting and their role in


code modularization.
Ability to write shell scripts using user-defined functions to
perform specific tasks.
Knowledge of function parameters, return values, and function
invocation.
Familiarity with recursion and its usage in shell scripting.

 Printing different shapes using shell script:

Ability to write shell scripts to print various shapes like diamond,


triangle, square, rectangle, etc.
Understanding of looping constructs and pattern printing in shell
scripting.
Knowledge of formatting output and using loops to control shape
size and dimensions.

 Shell Programming – Arrays:

Understanding of arrays in shell scripting and their usage for


storing and manipulating data.
Ability to write shell scripts to perform operations on arrays such
as reading, printing, searching, sorting, etc.
Knowledge of array indexing, array manipulation, and array-
based algorithms.
Familiarity with array traversal techniques and basic array
algorithms.

You might also like