100% found this document useful (1 vote)
1K views

Experiment-1 Write A Shell Script To Print The Command Line Arguments in Reverse Order

The script sorts an array in ascending order using bubble sort by: 1) Comparing adjacent elements and swapping

Uploaded by

ANKIT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

Experiment-1 Write A Shell Script To Print The Command Line Arguments in Reverse Order

The script sorts an array in ascending order using bubble sort by: 1) Comparing adjacent elements and swapping

Uploaded by

ANKIT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Experiment-1

Write a Shell script to print the command line arguments in reverse order.
#!/bin/sh
if [ $# -eq 00 ]
then
echo "no arguments given"
exit
fi
echo "Total number of arguments: $#"
echo "The arguments are: $*"
echo "The arguments in reverse order:"
rev=" "
for i in $*
do
rev=$i" "$rev
done
echo $rev

Output 1
$ ./print-arguments-in-reverse.sh
no arguments given

Output 2
$ ./print-arguments-in-reverse.sh 9 abc hello
Total number of arguments: 3
The arguments are: 9 abc hello
The arguments in reverse order:
hello abc 9
Experiment 2

Write a Shell script to check whether the given number is palindrome or not.
echo enter n
read n
num=0
on=$n
while [ $n -gt 0 ]
do
num=$(expr $num \* 10)
k=$(expr $n % 10)
num=$(expr $num + $k)
n=$(expr $n / 10)
done
if [ $num -eq $on ]
then
echo palindrome
else
echo not palindrome
fi

OUTPUT:

$ enter n
$ 121
$ palindrome
EXPERIMENT 3

Write a Shell script to sort the given array elements in ascending order using bubble sort.
# Sorting the array in Bash 
# using Bubble sort

# Static input of Array


arr=(10 8 20 100 12)
  
echo "Array in original order"
echo ${arr[*]}
  
# Performing Bubble sort 
for ((i = 0; i<5; i++))
do   
    for((j = 0; j<5-i-1; j++))
    do   
        if [ ${arr[j]} -gt ${arr[$((j+1))]} ]
        then
            # swap
            temp=${arr[j]}
            arr[$j]=${arr[$((j+1))]}  
            arr[$((j+1))]=$temp
        fi
    done
done
  
echo "Array in sorted order :"
echo ${arr[*]}

Output :

Array in sorted order :


8 10 12 20 100
EXPERIMENT 4

• Write a Shell script to perform sequential search on a given array elements.

echo Enter the number of elements:

read n

echo Enter the array elements:

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

do

read a[$i]

done

echo Enter the element to be searched:

read item

j=1

while [ $j -lt $n -a $item -ne ${a[$j]} ]

do

j=`expr $j + 1`

done

if [ $item -eq ${a[$j]} ]

then

echo $item is present at location $j

else

echo "$item is not present in the array."

fi
Experiment 5-
Write a Shell script to perform binary search on a given array elements.
echo “Enter the limit:”
read n
echo “Enter the numbers”
for(( i=0 ;i<n; i++ ))
do
read m
a[i]=$m
done
for(( i=1; i<n; i++ ))
do
for(( j=0; j<n-i; j++))
do
if [ ${a[$j]} -gt ${a[$j+1]} ]
then
t=${a[$j]}
a[$j]=${a[$j+1]}
a[$j+1]=$t
fi
done
done
echo “Sorted array is”
for(( i=0; i<n; i++ ))
do
echo “${a[$i]}”
done
echo “Enter the element to be searched :”
read s
l=0
c=0
u=$(($n-1))
while [ $l -le $u ]
do
mid=$(((( $l+$u ))/2 ))
if [ $s -eq ${a[$mid]} ]
then
c=1
break
elif [ $s -lt ${a[$mid]} ]
then
u=$(($mid-1))
else
l=$(($mid+1))
fi
done
if [ $c -eq 1 ]
then
echo “Element found at position $(($mid+1))”
else
echo “Element not found”
fi

OUTPUT
Enter the limit:  5
Enter the numbers
42637
Sorted array is
23467
Enter the number to be searched :7
Element found in position 5
EXPERIMENT 6-
Write a Shell script to accept any two file names and check their file permissions

if [ $# -ne 2 ]
then
echo "no arguments pls enter 2 arguments"
elif [ ! -e $1 -o ! -e $2 ]
then
echo "File does not exist"
else
per1=`ls -l $1 | cut -c 2-10`
per2=`ls -l $2 | cut -c 2-10`
if [ $per1 = $per2 ]
then
echo "Permissions are Identical:permission is $per1"
else
echo "Permissions are not Identical"
echo "permission of $1 is $per1"
echo "permission of $2 is $per2"
fi
fi

OUTPUT:
sh 8a.sh
no arguments please enter 2 arguments
sh 8a.sh 1.c 2.c
Permissions are Identical: permission is rw-r--r—
chmod 777 1.c
sh 8a.sh 1.c 2.c
Permissions are not Identical
permission of 1.c is rwxrwxrwx
permission of 2.c is rw-r--r—
Experiment-7
• Write a Shell script to read a path name, create each element in that path e.g: a/b/c
i.e., ‘a’ is directory in the current working directory, under ‘a’ create ‘b’, under ‘b’ create ‘c’

#!/usr/bin/python
import sys
import os.path
if len(sys.argv)>1:
for i in range(1,len(sys.argv)):
print os.path.abspath( sys.argv[i] )
sys.exit(0)
else:
print >> sys.stderr, "Usage: ",sys.argv[0]," PATH."
sys.exit(1)
EXPERIMENT 8-
Write a Shell script to illustrate the case-statement.

$ cat signal.sh
#!/bin/bash

if [ $# -lt 2 ]
then
echo "Usage : $0 Signalnumber PID"
exit
fi

case "$1" in

1) echo "Sending SIGHUP signal"


kill -SIGHUP $2
;;
2) echo "Sending SIGINT signal"
kill -SIGINT $2
;;
3) echo "Sending SIGQUIT signal"
kill -SIGQUIT $2
;;
9) echo "Sending SIGKILL signal"
kill -SIGKILL $2
;;
*) echo "Signal number $1 is not processed"
;;
Esac

$ sleep 1000

$ ps -a | grep sleep
23277 pts/2 00:00:00 sleep

$ ./signal.sh 9 23277
Sending SIGKILL signal

$ sleep 1000
Killed
Q 9:-Write a Shell script to accept the file name as arguments and create another shell

script, which recreates these files with its original contents.

#!/bin/bash

echo “Enter the file path”

read FILE

if [ -f “$FILE” ]

then

echo “$FILE is a reguler file”

elif [ -d “$FILE” ]

then

echo “$FILE is a directory”

else

echo “$FILE is another type of file”

fi

ls -l $FILE

output

[svimukthi@sanka Shell_Scripting]$ ./exe6.sh

Enter the file path

/home/svimukthi/sanka

/home/svimukthi/sanka is a directory

total 4

drwxr-xr-x. 2 svimukthi svimukthi 30 Nov 13 20:18 hs

-rw-rw-r — . 1 svimukthi svimukthi 12 Nov 12 12:09 sanka.txt

d — x — — — . 2 svimukthi svimukthi 20 Dec 13 18:53 test


EXPERIMENT10

Write a Shell script to demonstrate Terminal locking.

echo "\nEnter the password:\c"


stty -echo
read pass1
echo "\nRetypr password"
read pass2
if [ $pass1 = $pass2 ] ; then
tput clear
echo "\nThe terminal is locked\n"
echo "\nEnter password to unlock:"
read pass3
while [ $pass1 != $pass3 ]
do
echo "\nEnter password to unlock"
read pass3
done
else
echo "\nTerminal could not be locked"
fi
stty echo

EXPERIMENT 11
Write a Shell script to accept the valid login name, if the login name is
valid then print its home directory else an appropriate message.

#!/bin/bash
# getlogin-name.sh : A shell script to display login name
 
## Let us change variable values ##
USER="foo"
LOGNAME="bar"
 
## Greet user ##
## Display imposter name i.e. you can not trust $USER and $LOGNAME ##
echo "Hi,$USER! You are Imposter, for sure. Sorry, I can not trust you."
echo "Hello, $LOGNAME! You are Imposter, for sure. I cannot trust you. Go away! "
 
## Display real login name ##
echo "Hello, $(logname)! Let us be friends."

SAMPLE OUTPUTS-
Hi,foo! You are Imposter, for sure. Sorry, I can not trust you.
Hello, bar! You are Imposter, for sure. I cannot trust you. Go away!
Hello, vivek! Let us be friends.

EXPERIMENT 12
Write a Shell script to read a file name and change the existing file
permissions.

#!/bin/bash
file=~/scripts/text.txt

if [ -e $file ]
then echo "The file exists"

elif [ ! -e $file ]
then echo "The file does NOT exist"

fi

sleep 1s

if [ ! -w $file ]
then { sudo chmod u+w $file; } && { echo "The file is now writable"; }

elif [ -w $file ]
then echo "The file is already writable"
fi

EXPERIMENT 13

Write a Shell script to print current month calendar and to replace the current day number by ‘*’ or
‘**’ respectively.
set `date`
y=$3
if [ $y -le 9 ]
then
cal |sed "s/$3/*/"
else
cal |sed "s/$3/**/"
fi

EXPERIMENT 14
Write a Shell Script to display a menu consisting of options to display disk space, the

current users logged in, total memory usage, etc. ( using functions.)

#!/bin/bash

# function to show memory usage


memoryUsage(){
echo "Memory Usage:"
free
read -p "Press any key to Continue...."
}

# function to show disk usage


diskUsage(){
echo "Disk Usage:"
df
read -p "Press any key to Continue...."
}

# function to show menu


show_menu()
{
clear
echo "++++++++++++ MENU +++++++++++++"
echo "1. Show Memory Usage."
echo "2. Show DIsk Usage."
echo "3. Exit"
echo "+++++++++++++++++++++++++++++++"
}

# function to take input


take_input()
{
#take the input and store it in choice variable
local choice
read -p "Select the option from above menu: " choice

#using swich case statement check the choice and call function.
case $choice in
1) memoryUsage ;;
2) diskUsage ;;
3) exit 0;;
*) echo "Enter Valid Option!!"
read -p "Press any key to Continue...."

esac
}

# for loop to call the show_menu and take_input function.


while true
do
show_menu
take_input
done

EXPERIMENT 15
Write a C-program to fork a child process and execute the given Linux commands.

#include <stdio.h>

#include <sys/types.h>

#include <unistd.h>

int main()

fork();

fork();

fork();

fork();

printf("Using fork() system call");

return 0;

output

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

Using fork() system call

EXPERIMENT 16
Write a C-program to fork a child process, print owner process ID and its parent
process ID.
#include<stdio.h>
#include <unistd.h>
int main()
{

int i;
printf("hello before fork \n");
printf("i : %d\n",i);

i=fork();
printf("\n");

if(i==0)
{

printf("Child has started\n\n");


printf("child printing first time \n");

printf("getpid : %d getppid : %d \n",getpid(),getppid());


sleep(5);
printf("\nchild printing second time \n");
printf("getpid : %d getppid : %d \n",getpid(),getppid());
}
else
{
printf("parent has started\n");
printf("getpid : %d getppid : %d \n",getpid(),getppid());
printf("\n");

printf("Hi after fork i : %d\n",i);

return 0;

output

[04mca8@LINTEL pp]$ ./a.out


hello before fork
i : 134514088

Child has started

child printing first time


getpid : 8354 getppid : 8353

parent has started


getpid : 8353 getppid : 5656

Hi after fork i : 8354


[04mca8@LINTEL pp]$
child printing second time
getpid : 8354 getppid : 1
Hi after fork i : 0

EXPERIMENT 17
Write a C-program to prompt the user for the name of the environment variable, check
its validity and print an appropriate message.

#include <stdio.h>

int main(int argc, char *argv[], char * envp[])


{
int i;
for (i = 0; envp[i] != NULL; i++)
printf("\n%s", envp[i]);
getchar();
return 0;
}

output

ALLUSERSPROFILE=C:\ProgramData
CommonProgramFiles=C:\Program Files\Common Files
HOMEDRIVE=C:
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE=x86
PROCESSOR_IDENTIFIER=x86 Family 6 Model 42 Stepping 7, GenuineIntel
PROCESSOR_LEVEL=6
PROCESSOR_REVISION=2a07
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
WATCOM=C:\watcom
windir=C:\Windows

EXPERIMENT 18
Write a C-program to READ details of N students such as student name, reg number,
semester and age. Find the eldest of them and display his details.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Student {
char* name;
int id;
char age;
};

int comparator(const void* p, const void* q)


{
return strcmp(((struct Student*)p)->name,
((struct Student*)q)->name);
}

int main()
{
int i = 0, n = 5;

struct Student arr[n];

arr[0].id = 1;
arr[0].name = "bd";
arr[0].age = 12;

arr[1].id = 2;
arr[1].name = "ba";
arr[1].age = 10;

arr[2].id = 3;
arr[2].name = "bc";
arr[2].age = 8;

arr[3].id = 4;
arr[3].name = "aaz";
arr[3].age = 9;

arr[4].id = 5;
arr[4].name = "az";
arr[4].age = 10;

printf("Unsorted Student Records:\n");


for (i = 0; i < n; i++) {
printf("Id = %d, Name = %s, Age = %d \n",
arr[i].id, arr[i].name, arr[i].age);
}

qsort(arr, n, sizeof(struct Student), comparator);

printf("\n\nStudent Records sorted by Name:\n");


for (i = 0; i < n; i++) {
printf("Id = %d, Name = %s, Age = %d \n",
arr[i].id, arr[i].name, arr[i].age);
}

return 0;
}
output

Unsorted Student Records:


Id = 1, Name = bd, Age = 12
Id = 2, Name = ba, Age = 10
Id = 3, Name = bc, Age = 8
Id = 4, Name = aaz, Age = 9
Id = 5, Name = az, Age = 10

Student Records sorted by Name:


Id = 4, Name = aaz, Age = 9
Id = 5, Name = az, Age = 10
Id = 2, Name = ba, Age = 10
Id = 3, Name = bc, Age = 8
Id = 1, Name = bd, Age = 12

You might also like