0% found this document useful (0 votes)
16 views12 pages

21EC3A1 - Lab Experiments

The document outlines lab experiments for a Unix and Shell Scripting course for Electronics and Communication Engineering students. It includes detailed instructions for various exercises, such as using the date command, creating directories, and writing shell scripts, along with assessment rubrics. Additionally, it provides references for further learning and includes viva questions related to the course content.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views12 pages

21EC3A1 - Lab Experiments

The document outlines lab experiments for a Unix and Shell Scripting course for Electronics and Communication Engineering students. It includes detailed instructions for various exercises, such as using the date command, creating directories, and writing shell scripts, along with assessment rubrics. Additionally, it provides references for further learning and includes viva questions related to the course content.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Electronics and Communication Engineering 3rd Sem

Ability Enhancement Course – Unix and Shell Scripting

21EC3A1 – Unix and Shell Programming

Lab Experiments

After finishing each session, write a report that explains the result of each step
and answer any questions asked.

Note: Make use of the following link/s to know more about the shell
programming
Ref:
1. Shell Programming: http://www.freeos.com/guides/lsst/ch02.html
2. Python Reference: https://docs.python.org/3/tutorial/index.html
3. Perl: https://perldoc.perl.org/
Rubrics:
1. Execution of the programs and commands – 5 Marks
2. Submission of the Record book with Observations – 5 Marks
3. Attendance – 5 Marks
4. Answering VIVA Questions – 5 Marks
Each Week they are going to score 20 points. If they are absent they lose all
those marks of that week.
Have the Print out of the students batch wise to evaluate them.

Exp 1 Answer the following questions about the date command:


a. How many lines do you see in the result?
b. How many characters are in the result (including spaces)? Is the
total number of characters different if the day of the month is one
digit or two? d. How many characters define the date (day)? Show
the date format. e. How many characters define the time (hours
and minutes)? Show the time format.

1. Log into the system.


2. Use the date command to find the local time.
3. Use the date command to find the universal time.
4. What is the difference between your local time and the
universal time? Is your local time ahead of or behind the
universal time?
Electronics and Communication Engineering 3rd Sem
Ability Enhancement Course – Unix and Shell Scripting

5. Use all of the date arguments one by one and write a brief
explanation of the results.

6. What do you get if you use the following commands?


$ date "+This is the date"
$ date "+This is the date: $B"

7. Write a command to show the date using the following


formats:
05/21/99
Friday, May 21, 1999
Friday, 05/21/1999

8. Write a command to show the date using each of the


following formats
d. Day: Friday
Month: May
Year: 1999
9. Write a command to show the time using each of the
following formats:
d. 08:22:24 PM
b. 08:22 PM
. 08 AM
10. Write a command to show the time using each of the
following formats:
Hours: 08
b. Hours: 08 Minutes 22
Hours: 08 Minutes : 22 Seconds: 24
Log out of the system.

Exp 2 SESSION I

1. Log into the system.


2. Create three directories named 1etters, reports, and
assignments under your home directory.
3. Move to directory 1etters.
4. Create two directories named friendly and formal under the
letters directory.
5. Move to directory reports using only one command (directy
from letters).
6. Create three directories called personal, business, and school
under the directory reports (use only one command).
7. Create a directory called UNIX under the assignments
directory without moving from the reports directory
8. Create two directories called HWs and Projects under
directory UNIX. The directories in this step should be created
without moving from the reports directory.
Electronics and Communication Engineering 3rd Sem
Ability Enhancement Course – Unix and Shell Scripting

9. Move to your home directory.


10. Recursively list all of the directories you created and draw the
directory structure on paper.
11. Log out of the system.

Session 2
1. Log into the system.
2. Recursively list the directories under your home directory (the
ones created in Session I).
3. Move to the UNIX directory.
4. Check your current directory.
5. Using vi, create a file named hw4 that contains short answers to
at least five review questions in this chapter.
6. Save the file (it should be saved under the UNIX directory).
7. Move to your home directory.
8. Print the content of hw4 from your home directory.
9 Make a copy of hw4 and call it hw4.bk. Store it under the same
directory where hw4 is stored.
10. From your home directory, check to see if both files (hw4 and
hw4.bk) exist.
11. Move to the UNIx directory.
12. Check your current working directory.
13. Make a hard link to the hw4 file. The link should be under the
UNIX subdirectory and be called hw4HL.
14. Make a soft link to hw4 called hwa SL and store it under the
UNIX directory.
15. Check the inode of hw4, hw4.bk, hw4HL, and hw4SL. Are all the
same? Are all different? Explain how you determined the answer.
15 Use the is command to find the file types of hw4, hwa. bk,
hw4HL, and hw4 SL. Explain your observation.
17 Log out of the system.

Exp 3 SESSION 3:
1. Log into the system.
Create a backup directory in your home directory called backups.
Use the find command to find the pathnames of all of the files
(hw4, hw4.bk, hwds and hw4SL) that you created in Session IL. All
of them should be found using only o
find command. The command must also copy all of them to the
backups directorv
4. Check the number of links and inode number of hw4, hw4. bk,
hw3HL, and hw4SL. Make note of the results.
5. Delete the original hw4 file without moving from your home
directory.
6. Check the existence of hw4, hw4.bk, hw4HL, and hw4SL.
7. Check the contents of hw4, hw4.bk, hw4HL, and hw4SL.
Electronics and Communication Engineering 3rd Sem
Ability Enhancement Course – Unix and Shell Scripting

8. Restore the file hw4 by making a copy of hw4.bk.


9. You may have noticed that your soft link (hw4SL) contains
garbage. Delete this file.
10. Make a new soft link to hw4 and store it as hw4SL under the
same directory as it was,
11. List recursively all of your files and directories to confirm all
operations.
12. Draw the file and directory structure of your home directory.
13. Log out of the system.

Session IV
1. Log into the system.
2. Use wildcards to display all of the files you have created under
the HWs directory
without moving from your home directory.
Rename hw4.bk to hw4.bak.
4. Create a short friendly letter, called friend. 1, using vi and store it
under the
friendly directory.
Create a short formal letter, called formal.1, using vi and store it
under the
formal directory. Give a title to formal.1 letter.
6. Copy the file formal.1 and call the new copy formal .2.
7. Change only the title of formal .2 (using vi) and store it.
8. Using wildcards, print the contents of formal.1 and formal.2.
9. Make a directory called busLetters under your home directory.
10. Move the formal directory (with all of its contents) under the
busLetters directory.
11. Make a recursive list of your directory structure.
12. Draw the new directory structure on paper.
13. Log out of the system.
Exp 4 1)Write a shell script that accept a file name number of lines as
arguments and display all the lines from starting number?
THEORY:
Cat: cat command is used to create the file
Syntax: cat > file name for creation
Syntax: cat file name for displaying a file

man ls > lsman (it runs man command and dumps it in lsman file
name)

Cat: cat runs the catalogue on given file name.

$ open the a readnlines.sh (vi or cat > readnlines.sh)


#!/bin/bash

Echo -n “Enter the filename: “


Electronics and Communication Engineering 3rd Sem
Ability Enhancement Course – Unix and Shell Scripting

Read file
Echo -n “Enter number of lines to read: “
Read lines
Cat $file | head -n $lines
^z (Ctrl+z) # closes the file
$ chmod u+x readnlines.sh
$ ./readnlines.sh (Run the script)

2. Write another shell file to read from the bottom of the file (use
tail -n $lines)
3. Write a shell script which will give 10 random numbers between
300 and 1000.

Generate Random number between two numbers

cat random.sh
#!/bin/bash
echo -n "Enter the Min number > 100:"
#MIN=200
read MIN
echo -n "Enter the Max number < 1000:"
#MAX=500
read MAX
let “scope = $MAX - $MIN”
if [ “$scope” -le “0” ]; then
echo “Error - MAX is less than MIN!”
fi
for i in `seq 1 10`
do
let result=”$RANDOM % $scope + $MIN”
echo “A random number between $MIN and $MAX is $result”
done

VIVA QUESTIONS
1.what is a file system?
2.why we are using head command?
3.which command is used to create file?
4.why we are using chmod?
5.which permissions are provided to files?
Exp 5 3)Write a shell script that displays a list of all the files in the current
directory to which the user has read, write and execute
permissions?
THEORY:
Cd: The cd command can be used for to change the directory that
means we can change the existing directory.
Electronics and Communication Engineering 3rd Sem
Ability Enhancement Course – Unix and Shell Scripting

Wc: The wc command can be used for to count the number of


words on given data by using wc command options we can count
the number of lines on a file (wc-l).

echo "enter the directory name"


read dir
if [ -d $dir ]
then
cd $dir
ls > f
exec < f
while read line
do
if [ -f $line ]
then
if [ -r $line -a -w $line -a -x $line ]
then
echo "$line has all permissions"
else
echo "files not having all permissions"
fi
fi
done
Write a shell script that receives any number of file names as
arguments checks if every argument supplied is a file or a
directory and reports accordingly, whenever the argument is a file
or directory.
Ans)
for x in $*
do
if [ -f $x ]
then
echo " $x is a file "
echo " no of lines in the file are "
wc -l $x
elif [ -d $x ]
then
echo " $x is a directory "
else
echo " enter valid filename or directory name "
fi
done

VIVA QUESTIONS:
1.what is a directory?
2.which command is used to create directory?
3.what is the purpose of wc cmd?
Electronics and Communication Engineering 3rd Sem
Ability Enhancement Course – Unix and Shell Scripting

4.which command is used to change the directory


Exp 6 a) Write a program to demonstrate different number datatypes
in python.

Source code:
i=7
c=24+8j
f=701
s='HELLO EVERYONE!!\nThis is john\'s python programming..'
# NOTE: boolean has truth values that are case sensitive Ex: True (T
is caps!)
b= True
print("the value of c is:",i,'\nits type is:',type(i))
print("the value of c is:",f,'\nits type is:',type(f))
print("the value of c is:",c,'\nits type is:',type(c))
print("the value of c is:",s,'\nits type is:',type(s))
rint("the value of c is:",b,'\nits type is:',type(b))
print('NOTE: boolean has truth values that are case sensitive Ex:
True (T is caps!)')
b) Write a program to perform different arithematic operations
on numbers in python
Source code:
a=10; b=3
print("addition of a:",a,"&b:",b,"is:",a+b)
print("substraction of a:",a,"&b:",b,"is:",a-b)
print("multiplication of a:",a,"&b:",b,"is:",a*b)
print("division of a:",a,"&b:",b,"is:",a/b)
print("floor divison of a:",a,"&b:",b,"is:",a//b)
print("moduli of a:",a,"&b:",b,"is:",a%b)
print("exponent of a:",a,"&b:",b,"is:",a**b)
Exp 7 1. Write a Python program to guess a number between 1 to 9.
Note : User is prompted to enter a guess. If the user guesses wrong
then
the prompt appears again until the guess is correct, on successful
guess,
user will get a "Well guessed!" message, and the program will exit.

2. Write a Python program to check whether an alphabet is a vowel


or consonant.
Expected Output:
Input a letter of the alphabet: k
k is a consonant.

3. Write a Python program that prints all the numbers from 0 to 6


except 3
and 6.
Note : Use 'continue' statement.
Electronics and Communication Engineering 3rd Sem
Ability Enhancement Course – Unix and Shell Scripting

Expected Output : 0 1 2 4 5

5. Write a Python program to get the Fibonacci series between


0 to 50.
Note : The Fibonacci Sequence is the series of numbers :
0, 1, 1, 2, 3, 5, 8, 13, 21, ....
Every next number is found by adding up the two numbers before
it.
Expected Output : 1 1 2 3 5 8 13 21 34

Write a Python program to create the multiplication table (from 1


to 10) of a
number. (using ‘for’ loop only)
Expected Output:
Input a number: 6
6x1=6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
Exp 8 1. Write a Python function that takes a list and returns a new list
with unique
elements of the first list
Hint: def newlist(oldlist):
newlist = []
for each ele in oldlist
if ele in newlist:
continue
else:
newlist.append(ele)
return newlist

2. Write a Python program to print the even numbers from a given


list.
Hint: Similar to the above logic is to check that it is divided by 2
(num%2==0)

3. Find the largest item from a given list


x = [4, 6, 8, 24, 12, 2], excepted output=24
Hint: check each ele in the list and find the max of the list

4. Write a Python program to multiply all the items in a list.


Electronics and Communication Engineering 3rd Sem
Ability Enhancement Course – Unix and Shell Scripting

Hint: have a for loop and visit each ele and multiply the result with
each ele.

5. Write a Python program to Check if given 2 strings are anagrams.


[Two strings are anagrams if they are written using the same letters
(ignoring case).
eg: 'Mary and Army', 'Silent' and 'Listen' are anagrams]

6.Write a function that takes a list of numbers and returns the


cumulative sum, i.e., a new list where
the 'i'th element is the sum of the first 'i+1' elements from the
original list.
eg: the cumulative sum of [1, 2, 3, 4] is [1, 3, 6, 10]
7. Write a python program to accept a sentence into a string
variable. Then print the 1st letter of the 3 word in the sentence.
Exp 9 Exercise 1: Write a program to check whether a given key exists in a
dictionary or not

Hint
Given dict = {‘0’:1, ‘1’:2, ‘2’:3}
Input:
Enter value to check: 2
Expected output
Result: True

Exercise 2: Write a program to iterate over dictionary items using for


loop

Hint
dict = {0:”Value 1″, 1:”Value 2″}
Expected output
Value of key 0 is Value 1
Value of key 1 is Value 2

Exercise 3: Python program to sort dictionary by values (Ascending/


Descending).

Hint
Given
d = {‘key 1’: 2, ‘key 2’: 3, ‘key 3’: 4}
Expected output
Ascending: [(‘key 1’, 2), (‘key 2’, 3), (‘key 3’, 4)]
Descending: [(‘key 3’, 4), (‘key 2’, 3), (‘key 1’, 2)]

Exercise 4: Write a program to sum all the values of a dictionary.


Electronics and Communication Engineering 3rd Sem
Ability Enhancement Course – Unix and Shell Scripting

Hint
dict1 = {‘key 1’: 200, ‘key 2’: 300}
Expected output
Result: 500

Exercise 5: Write a program to get the maximum and minimum


value of dictionary.

Hint
dict1 = {‘key 1’: 200, ‘key 2’: 300}
Expected output
Max: 300
Min: 200

Exercise 6: Write a program in Python to remove repetitive items


from a list

Hint
Given num = [2,3,4,5,2,6,3,2]
Expected output
Result: [2, 3, 4, 5, 6]

Exercise 7: Write a Python program that creates from a keyboard-


typed integer n, a dictionary whose keys are integers from 1 to n
and key values are their squares. Example for n = 7 the dictionary
will be of the form:
{1: 1, 2: 4, 3: 9, 4:16, 5:25, 6:36, 7:49}

Exp 10 Write a python program to convert temperature to and from


Celsius to fahrenheit.

Source code:
while(1):
print("1.CELSIUS TO FAHRENHEIT\n2.FAHRENHEIT TO
CELSIUS\n3.EXIT\n")
choice=input("ENTER YOUR CHOICE:")
ch=int(choice)
if(ch==1):
c=int(input("ENTER TEMPERATURE IN CELSIUS:"))
f=((9*c)/5)+32
print("converted temperature is:",f)
elif(ch==2):
f=int(input("ENTER TEMPERATURE IN FAHRENHEIT:"))
c=((f-32)/9)*5
print("converted temperature is:",c)
elif(ch==3):
exit()
Electronics and Communication Engineering 3rd Sem
Ability Enhancement Course – Unix and Shell Scripting

else:
print("wrong choice")

Write a python program to construct the following pattern using


nested for loop:
*
**
***
****
*****
*****
****
***
**
*
Source code:
n=int(input("ENTER A VALUE:"))
for x in range(0,n+1,1):
print(x*'*')
if(x==n):
for x in range(n,0,-1): print(x*'*')
Exp 11 Write a python program to find factorial of a number using
recursion:
Source code:
def recursion(n):
if(n<1):
print("FACTORIAL NOT POSSIBLE!!")
elif(n>1):
return n*recursion(n-1)
else:
return 1
n=int(input("enter a number:"))
print("factorial of",n,"is:",recursion(n))

Write a script named copyfile.py. This script should prompt the user
for the
names of two text files. The contents of the first
the second file.
Source code:
Note: create a text file as “input.txt” and write some date in it. This
will be used in the program.
with open("input.txt") as input:
with open("output.txt","w") as
for line in input: output.write(line)
print("JOB DONE!!")
Exp 12 Write a program that inputs a text file. The program should print all
of the
Electronics and Communication Engineering 3rd Sem
Ability Enhancement Course – Unix and Shell Scripting

unique words in the file in alphabetical order.


Source code:
fname=input("enter file name with correct extension:")
file_opened=open(fname)
our_list=list() #creating an empty list
for line in file_opened:
word=line.rstrip().split() #rstrip for removing unwanted spaces
for element in word:
if element in our_list:
continue
else:
our_list.append(element)
our_list.sort()
print(our_list)

Write a Python class to implement pow(x, n)


Source code:
class py_power:
def power(x,n):
print("power of given literals:\nx:",x,"\nn\n:",n,"is:",x**n)
x=float(input("ENTER X(BASE) VALUE:"))
n=float(input("ENTER N(POWER) VALUE:"))
py_power.power(x,n)
Exp 13 Write a Python class to reverse a string word by
Source code:
fname="HELLO EVERYONE THIS IS
WITH LISTS"
our_list=list()
word=fname.split()
for element in word:
our_list.append(element)
print("tried sentence is:",our_list)
our_list.reverse()
print("list after the reverse()",our_list)

Write a Python class to implement calculate arithmetic operations.

You might also like