KEMBAR78
JAVA Linux Bash Record | PDF | Computer File | System Software
0% found this document useful (0 votes)
25 views56 pages

JAVA Linux Bash Record

The document is a practical record for the Fourth Semester BCA program at Dr. APJ Abdul Kalam College of Professional Studies, detailing Java Programming, Shell Programming, and Linux Administration. It includes a certificate of authenticity, an index of programs, and sample Java code demonstrating various programming concepts and operations. The document serves as a comprehensive guide for students to fulfill their practical requirements for the BCA degree.

Uploaded by

yapaw47132
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)
25 views56 pages

JAVA Linux Bash Record

The document is a practical record for the Fourth Semester BCA program at Dr. APJ Abdul Kalam College of Professional Studies, detailing Java Programming, Shell Programming, and Linux Administration. It includes a certificate of authenticity, an index of programs, and sample Java code demonstrating various programming concepts and operations. The document serves as a comprehensive guide for students to fulfill their practical requirements for the BCA degree.

Uploaded by

yapaw47132
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/ 56

Dr.

APJ ABDUL KALAM COLLEGE OF PROFESSIONAL


STUDIES, ULIKKAL KANNUR

[ Affiliated to Kannur University ]

FOURTH SEMESTER BCA PRACTICAL RECORD


JAVA PROGRAMMING
&
SHELL PROGRAMMING
&
LINUX ADMINSTRATION
Dr. APJ ABDUL KALAM COLLEGE OF PROFESSIONAL
STUDIES, ULIKKAL KANNUR

[ Affiliated to Kannur University ]

Certificate
This is to certify that this is a bona-fide record work done by ____________
Reg. No _____________ in partial fulfilment of the requirements for the
provision of BCA Degree during fourth semester.

Teacher in charge Head of the Department

Examiner 1 : Principal

Examiner 2 :

Place :

Date :
INDEX

Sl No JAVA Programs Page No

1 program to perform various string operations 6


2 program to implement interface. 9
3 program that handles various exceptions. Use try-catch 10
statement.
4 program to implement file I/O operations using iostreams. 12
5 program to implement Applet life cycle. 14
6 program to implement a calculator using suitable AWT 16
controls.
7 program to implement packages. 19
8 With API support write demo program for menu display. 20
9 Menu driven program to demonstrate threads. 23
10 Demonstrate of FileInput Stream and FileOuput Stream 25
Classes.
INDEX

Sl No SHELL Programs Page No

1 Get a number from the user, create a file with the name 28
and number. Also display content of the file.
2 program to greet user by “Good Morning”, ”Good 30
afternoon” or “Good Evening ” based on time
3 program to check whether a number is positive, negative 31
or zero.
4 shell script to print a number in reverse order. 32
5 program to check whether a user has logged in or not. 33
User name is passed as command line argument.
6 demo program for number and string comparison 34
operators.
7 demo program using basic calculator 36
8 program to create 10 users. 38
9 program to test different file operators. 39
10 program with 3 different functions. use menu driven 41
program and invoke function accordingly.
INDEX

Sl No LINUX Administration Page No

1 Linux installation , upgradation ,installation and removal 46


of packages and installation of peripheral devices.
2 Starting and stopping services in run level. The service 47
command.
3 Managing process – viewing status, killing, restating etc 48
using ps command.
4 Adding and deleting user accounts, changing passwords. 50
5 Changing environmental variables like Path. 51
6 Scheduling job using cron. 52
7 Mounting and unmounting external file systems. 53
8 Setting value of mask, changing the permission, changing 54
owner and groups.
9 Archiving and backup using tar. Restoring and backup. 55
10 Compressing and uncompressing files using any one tool. 56
1. Write a Java program to perform various string operations using java class.

Program :

import java.util.Scanner;
class mtk
{
String a=new String();
String b=new String();
public void get()
{
Scanner n=new Scanner(System.in);
System.out.println("\n enter the string 1");
a=n.nextLine();
System.out.println("\n enter the string 2");
b=n.nextLine();
}
public void op()
{
char ch;
Scanner n=new Scanner(System.in);
do{
System.out.println("\n 1:concat() \n 2:lowercase() \n 3:uppercase() \n 4:equals() \n 5:length() \
n ");
System.out.println("enter the option ");
int o=n.nextInt();
switch(o)
{
case 1: System.out.println("concat () is used to combine strings \n");
a=a.concat(b);
System.out.println("concat string = "+a);
break;
case 2: System.out.println(" string 1 lower case = "+a.toLowerCase());
System.out.println(" string 2 lower case = "+b.toLowerCase());
break;
case 3:System.out.println(" string 1 upper case = "+a.toUpperCase());
System.out.println(" string 2 upper case = "+b.toUpperCase());
break;
case 4: boolean bool =a.equals(b);
if(bool== true){
System.out.println("Strings are equals");
}
else{
System.out.println("Strings are not same");
}
break;
case 5:int l=a.length();
System.out.println("length = " +l);
break;
}

6
System.out.println("do u need to continue (y/n)");
ch=n.next().charAt(0);
}while(ch=='y');
System.out.println("thank u!!");
}
public static void main(String args[])
{
mtk m=new mtk();
m.get();
m.op();
}
}

Output :

enter the string 1


hello

enter the string 2


world

1:concat()
2:lowercase()
3:uppercase()
4:equals()
5:length()

enter the option


1
concat () is used to combine strings

concat string = helloworld


do u need to continue (y/n)
y

1:concat()
2:lowercase()
3:uppercase()
4:equals()
5:length()

enter the option


2

7
string 1 lower case = helloworld
string 2 lower case = world
do u need to continue (y/n)
y

1:concat()
2:lowercase()
3:uppercase()
4:equals()
5:length()

enter the option


3
string 1 upper case = HELLOWORLD
string 2 upper case = WORLD
do u need to continue (y/n)
y

1:concat()
2:lowercase()
3:uppercase()
4:equals()
5:length()

enter the option


4
Strings are not same
do u need to continue (y/n)
y

1:concat()
2:lowercase()
3:uppercase()
4:equals()
5:length()

enter the option


5
length = 10
do u need to continue (y/n)
n
thank u!!

------------------
(program exited with code: 0)
Press return to continue

8
2. Write java program to implement interface.

Program :

import java.util.Scanner;
interface mtk
{
final static double p=3.14;
public double area(double r);
}
class intr implements mtk
{
public double area(double r)
{
double ar;
ar=p*r*r;
return ar;
}
public static void main(String args[])
{
Scanner n=new Scanner(System.in);
intr m=new intr();
double t,ar1;
System.out.println("\n enter the radius of circle ");
t=n.nextFloat();
ar1=m.area(t);
System.out.println("\n area = "+ar1);
}
}

Output :

enter the radius of circle


6

area = 113.03999999999999

9
3. Write java program that handles various exceptions. Use try-catch statement.

Program :

import java.util.Scanner;
class mtk
{
Scanner n= new Scanner(System.in);
void exp()
{
int a,b,res;
String s=new String();
String s1=new String();
String str1=null;
System.out.println("\n we are going to check some java exceptions \n");
try
{
System.out.println("\n arithmetic exception \n");
System.out.println(" enter the 2 no for div ");
a=n.nextInt();
b=n.nextInt();
res=a/b;
System.out.println("div= "+res);
}
catch(ArithmeticException e)
{
System.out.println(e);
System.out.println("divisor cant be zero \n");
}
try{
System.out.println("\n indexoutofbound exception \n");
System.out.println(" enter the string : ");
s=n.next();
int r;
System.out.println("enter the index to find the character : ");
r=n.nextInt();
System.out.println(s.charAt(r));
}
catch(StringIndexOutOfBoundsException e1)
{
System.out.println(e1);
}
try{
System.out.println("\n number format exception \n ");
System.out.println(" enter the string : ");
s1=n.next();
System.out.println(" trying to convert string to integer ");
int o=Integer.parseInt(s1);
System.out.println(" after converting string to integer " +o);

10
}
catch(NumberFormatException e2)
{
System.out.println(e2);
}
}
public static void main(String args[])
{
mtk m=new mtk();
m.exp();
}
}

Output :

we are going to check some java exceptions

arithmetic exception

enter the 2 no for div


34
div= 0

indexoutofbound exception

enter the string :


hi
enter the index to find the character :
0
h

number format exception

enter the string :


hello world
trying to convert string to integer
java.lang.NumberFormatException: For input string: "hello"

11
4. Write a java program to implement file I/O operations using iostreams.

Program :

import java.io.*;
import java.util.Scanner;
class fileio
{
public static void main(String args[]) throws IOException
{
Scanner n=new Scanner(System.in);
try
{
File f=new File("D:\\ filefile.txt");
if( f.createNewFile())
{
System.out.println(" file created \n file name = "+f.getName()+"\n path =
"+f.getAbsolutePath());
}
else
{
System.out.println("File already exists at path"+f.getAbsolutePath());
}
FileWriter f1= new FileWriter("D:\\ filefile.txt", true);
String str=new String();
System.out.println("enter the data to be inputted in file \n ");
str=n.nextLine();
f1.write(str);
f1.close();
Scanner n1=new Scanner(f);
System.out.println("data present in file = ");
while(n1.hasNextLine())
{
String data=n1.nextLine();
System.out.println(data);
}
n1.close();
}catch(IOException e)
{
System.out.println(e);
}
}
}

12
Output :

file created
file name = D:\ filefile.txt
path= /home/admin1/Documents/record/D:\ filefile.txt
enter the data to be inputted in file

helloworld
data present in file =
helloworld

13
5. Write a java program to implement Applet life cycle.

Program :

import java.awt.Graphics;
import java.awt.Font;
import java.awt.Color;
import java.util.Scanner;
public class apt extends java.applet.Applet
{
Font f = new Font("Times New Roman ",Font.BOLD,66);;
int a,b;
int rs;
Scanner s=new Scanner(System.in);
public void init()
{
System.out.println("init () called ");
System.out.println("enter two numbers : ");
a=s.nextInt();
b=s.nextInt();
}
public void start()
{
System.out.println("start () called ");
rs=a+b;
}
public void stop()
{
System.out.println("stop () called ");
System.out.println("result = "+rs);
}
public void paint(Graphics h)
{
h.setFont(f);
h.setColor(Color.green);
h.drawString("Hello", 25, 100);
h.setColor(Color.blue);
h.drawString("sum = "+rs,95,210);
}
public void destroy()
{
System.out.println("destroy() called ");
}
}

HTML Code
<html>
<title> applet </title>
<applet code="apt.class" width="1500" height="1000" ></applet>
</html>

14
Output :

15
6. Write a java program to implement a calculator using suitable AWT controls.

Program :

import java.awt.*;
import java.awt.event.*;
public class CalculatorAWT extends Frame implements ActionListener
{
// Declare the components
TextField textField;
Button[] numberButtons;
Button addButton, subButton, mulButton, divButton, eqButton, clearButton;
String operator = "";
double firstNum = 0, secondNum = 0, result = 0;
// Constructor to set up the calculator UI
public CalculatorAWT()
{
// Set frame title
setTitle("Simple Calculator");
// Create a TextField to display results
textField = new TextField();
textField.setBounds(30, 40, 280, 40);
// Create number buttons (0-9)
numberButtons = new Button[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new Button(String.valueOf(i));
numberButtons[i].addActionListener(this);
}// Create operator buttons (+, -, *, /)
addButton = new Button("+");
subButton = new Button("-");
mulButton = new Button("*");
divButton = new Button("/");
eqButton = new Button("=");
clearButton = new Button("C");
// Set bounds for the operator buttons
addButton.setBounds(30, 100, 50, 50);
subButton.setBounds(90, 100, 50, 50);
mulButton.setBounds(150, 100, 50, 50);
divButton.setBounds(210, 100, 50, 50);
eqButton.setBounds(270, 100, 50, 50);
clearButton.setBounds(270, 160, 50, 50);
// Set bounds for number buttons
int x = 30, y = 160;
for (int i = 1; i <= 9; i++) {
numberButtons[i].setBounds(x, y, 50, 50);
x += 60;
if (i % 3 == 0) {
x = 30;
y += 60;
}

16
}
numberButtons[0].setBounds(90, 280, 50, 50);// Add components to the frame
add(textField);
for (int i = 0; i < 10; i++) {
add(numberButtons[i]);
}
add(addButton);
add(subButton);
add(mulButton);
add(divButton);
add(eqButton);
add(clearButton);
// Set layout and frame properties
setLayout(null);
setSize(350, 380);
setVisible(true);
// Set window close behavior
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
// Add action listeners for the operator buttons
addButton.addActionListener(this);
subButton.addActionListener(this);
mulButton.addActionListener(this);divButton.addActionListener(this);
eqButton.addActionListener(this);
clearButton.addActionListener(this);
}
// Handle button click events
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if ((command.charAt(0) >= '0' && command.charAt(0) <= '9')) {
// If the button is a number, append it to the text field
textField.setText(textField.getText() + command);
} else if (command.charAt(0) == 'C') {
// Clear the text field
textField.setText("");
firstNum = secondNum = result = 0;
operator = "";
} else if (command.charAt(0) == '=') {
// Perform the calculation when "=" is clicked
secondNum = Double.parseDouble(textField.getText());
switch (operator) {
case "+":
result = firstNum + secondNum;
break;
case "-":
result = firstNum - secondNum;

17
break;
case "*":
result = firstNum * secondNum;break;
case "/":
if (secondNum != 0) {
result = firstNum / secondNum;
} else {
textField.setText("Error");
return;
}
break;
default:
result = secondNum;
}
textField.setText(String.valueOf(result));
operator = "";
} else {
// If the button is an operator, save the number and operator
if (!textField.getText().equals("")) {
firstNum = Double.parseDouble(textField.getText());
operator = command;
textField.setText("");
}
}
}
// Main method to run the calculator
public static void main(String[] args)
{
new CalculatorAWT();
}
}

Output :

18
7. Write a java program to implement packages.
Program :

Package 1 :
package pak1;
public class add
{
public int sum(int a,int b)
{
int s;
s=a+b;
return s;
}
}

Package 2:
package pak1;
import pak1.*;
import java.util.Scanner;
class imp
{
public static void main(String args[])
{
Scanner n=new Scanner(System.in);
add a=new add();
int t,c,v;
System.out.println("enter to numbers ");
c=n.nextInt();
v=n.nextInt();
t=a.sum(c,v);
System.out.println("sum="+t);
}
}

Output :

enter to numbers
10 20
sum=30

19
8. With API support write demo program for menu display.

Program :

import java.awt.*;
import java.awt.event.*;
public class MenuDisplayAWT extends Frame
{
// Constructor to set up the menu and the frame
public MenuDisplayAWT()
{
// Set the title of the frame
setTitle("AWT Menu Display Example");
// Create a TextArea to display selected options
TextArea textArea = new TextArea();
textArea.setEditable(false);
textArea.setBounds(30, 50, 400, 200);
// Create a menu bar
MenuBar menuBar = new MenuBar();
// Create a "File" menu
Menu fileMenu = new Menu("File");
// Create menu items for "File" menu
MenuItem newItem = new MenuItem("New");
MenuItem openItem = new MenuItem("Open");
MenuItem saveItem = new MenuItem("Save");
MenuItem exitItem = new MenuItem("Exit");// Add action listeners for "File" menu items
newItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
textArea.setText("You selected: New");
}
});
openItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
textArea.setText("You selected: Open");
}
});
saveItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
textArea.setText("You selected: Save");
}
});
exitItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)

20
{
System.exit(0); // Exit the program
}
});
// Add menu items to "File" menu
fileMenu.add(newItem);fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator(); // Adds a separator
fileMenu.add(exitItem);
// Create a "Help" menu
Menu helpMenu = new Menu("Help");
// Create "About" menu item for "Help"
MenuItem aboutItem = new MenuItem("About");
aboutItem.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
textArea.setText("You selected: About");
}
});
// Add the "About" item to the "Help" menu
helpMenu.add(aboutItem);
// Add menus to the menu bar
menuBar.add(fileMenu);
menuBar.add(helpMenu);
// Set the menu bar to the frame
setMenuBar(menuBar);
// Add the text area to the frame
add(textArea);// Set layout, size, and visibility
setLayout(null);
setSize(500, 300);
setVisible(true);
}
public static void main(String[] args)
{
// Create the frame with the menu
new MenuDisplayAWT();
// Close the application when the window is closed
WindowListener windowListener = new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
};
}
}

21
Output :

22
9. Write a java program to demonstrate threads.

Program :

import java.io.*;
class Newthread implements Runnable
{
String name;
Thread t;
Newthread(String threadname)
{
name=threadname;
t=new Thread(this,name);
System.out.println("New thread:"+t);
t.start();
}
public void run()
{
try
{
for(int i=5;i>0;i--)
{
System.out.println(name+";"+i);
Thread.sleep(1000);
}
}catch(InterruptedException e)
{
System.out.println(name +"Interrupted");
}
System.out.println(name+"existing");
}
}
class multithread
{
public static void main(String args[])
{
System.out.println("OUTPUT");
System.out.println("------------");
new Newthread("One");
new Newthread("Two");
new Newthread("Three");
try
{
Thread.sleep(10000);
}
catch(InterruptedException e)
{
System.out.println("Main Thread Interrupted.");
}
System.out.println("Main Thread existing.");

23
}
}

Output :

OUTPUT
------------
New thread:Thread[#19,One,5,main]
New thread:Thread[#20,Two,5,main]
New thread:Thread[#21,Three,5,main]
Three;5
One;5
Two;5
Three;4
One;4
Two;4
Three;3
One;3
Two;3
Three;2
One;2
Two;2
Three;1
One;1
Two;1
Oneexisting
Twoexisting
Threeexisting
Main Thread existing.

------------------
(program exited with code: 0)
Press return to continue

24
10 . Demonstrate of FileInput Stream and FileOuput Stream Classes.

Program :

import java.io.*;
import java.util.Scanner;
public class data
{
public static void main(String args[])
{
Scanner n=new Scanner(System.in);
try{
FileOutputStream o=new FileOutputStream("D:\\text.txt",true);
String s;
System.out.println("enter the string to write on the file ");
s=n.nextLine();
byte b[]=s.getBytes();
o.write(b);
o.close();
System.out.println("\n successfully written on the file ");
}catch(Exception e){
System.out.println(e);
}
try{
File file=new File("D:\\text.txt");
FileInputStream i=new FileInputStream(file);
byte b1[]= new byte[(int)file.length()];
i.read(b1);
String s=new String(b1);
System.out.println("\n file contents are :"+s);
}catch(Exception e1)
{
System.out.println(e1);
}
}
}

Output :

enter the string to write on the file


hello world

successfully written on the file

25
file contents are :hello world

------------------
(program exited with code: 0)
Press return to continue

26
SHELL PROGRAMMING

27
1.Get a number from the user, create a file with the name and
number. Also display content of the file.

• If the name is XXX and a number is 2 file name must be XXX_2

• Use cat command to create file

• Creating a file with 10 different lines, then display the first 5


lines of the file using head command.

Program :

#/bin/bash

echo enter the name

read name

echo enter a number

read num

filename="${name}_${num}.txt"

echo enter 10 lines to the file $filename and save by Ctrl + d

cat>$filename

echo -e “The first 5 lines of the file $filename are : ”

head -n 5 $filename

28
Output :

enter the name


sree
enter a number
4750
enter 10 lines to the file sree_4750.txt and save by Ctrl + d
h
he
hel
hell
hello
hellow
hellowo
hellowor
helloworl
helloworld
“The first 5 lines of the file sree_4750.txt are : ”
h
he
hel
hell
hello

29
2.write a program to greet user by “Good Morning”, ”Good
afternoon” or “Good Evening ” based on time

• Get system time using “date” command

• Read name from the user

• If the name is XXX then greet with “Hello XXX, Good Morning!”

Program:

#!/bin/bash

h=$(date +%H)

echo enter the name:

read name

if [ $h -le 12 ]

then

echo hello $name !! Good Morning !!

elif [ $h -le 16 ]

then

echo hello $name !! Good Afternoon !!

else

echo Hello $name !! Good evening !!

fi

Output :

enter the name:


sreehary
Hello sreehary !! Good evening !!

30
3.Shell program to check whether a number is positive, negative or
zero.

Program:

#!/bin/bash

echo enter the no:

read no

if [ $no -lt 0 ]

then
echo negative

elif [ $no -gt 0 ]

then

echo positive

else

echo zero

fi

Output:

enter the no:


1
positive

enter the no:


-1
negative

enter the no:


0
zero

31
4.shell script to print a number in reverse order.

Program:

#!/bin/bash

echo enter the no :

read n

k=0

num=0

while [ $n -gt 0 ]

do

num=$(expr $num \* 10 )

k=$(expr $n % 10)

num=$(expr $num + $k)

n=$(expr $n / 10)

done

echo no after reversing = $num

Output:

enter the no :
456
no after reversing = 654

32
5.Write a program to check whether a user has logged in or not.
User name is passed as command line argument.

Program:

#!/bin/bash

if [ $# -lt 1 ]

then

echo " plz give user name"

exit

fi

user=$1

log=0

for u in $(getent passwd | awk -F: '{ print $1}')

do

if [ "$user" == "$u" ]
then

echo user logged in

log=1

fi
done

if [ $log -eq 0 ]

then

echo "user not logged in"

fi

Output:

./program5.sh system
system user not logged in

./program5.sh sreehary
sreehary user logged in

33
6.Write a demo program for number and string comparison operators

• Verify whether the entered username and password is of admin


users if so display a warning message ‘permission denied’.

• Read a number from the user. Check whether number of files in


folder is greater than the read number.

Program:

ADMIN_USERNAME="admin"

ADMIN_PASSWORD="admin123"

read -p "Enter username:" entered_username

read -sp "Enter password" entered_password

echo $entered_username

if [ "$entered_username" == "$ADMIN_USERNAME" ] && [ "$entered_password" ==


"$ADMIN_PASSWORD" ]

then

echo "Access Granted"

else

echo "Permission Denied"

fi

output:

Enter username:admin
Enter passwordadmin
Access Granted

34
7 . Read a number from the user. Check whether number of files in
folder is greater than the read number.

Program:

#!/bin/bash

read -p "Enter a number: " entered_number

if ! [[ "$entered_number" =~ ^[0-9]+$ ]]; then

echo "Please enter a valid number."

exit 1

fi

read -p "Enter the folder path: " folder_path

if [ ! -d "$folder_path" ]; then

echo "The provided path is not a valid directory."

exit 1

fi

file_count=$(find "$folder_path" -maxdepth 1 -type f | wc -l)

if [ "$file_count" -gt "$entered_number" ]; then

echo "The number of files in the folder is greater than $entered_number."

else

echo "The number of files in the folder is not greater than $entered_number."

fi

output:

Enter a number: 6
Enter the folder path: /home/sreehary/Downloads/Shell Script
The number of files in the folder is greater than 6.

Enter a number: 15
Enter the folder path: /home/sreehary/Downloads/Shell Script
The number of files in the folder is not greater than 15.

35
7.write a demo program using basic calculator

• Find the average size of files available in a folder

program:

#!/bin/bash

#check if a directory is provided

if [ -z "$1" ]; then
echo "Usage: $0 <directory> path should provided as command line argument."
exit 1
fi

#check if the directory exists


if [ ! -d "$1" ]; then
echo "The provided path is not a valid directory."
exit 1
fi

#initialize variables to calculate the total size and count of files

total_size=0
file_count=0

#loop through each file in the directory

for file in "$1"/*; do


if [ -f "$file" ]; then

#get the size of the file

file_size=$(stat --format="%s" "$file")

#add the size to total_size

total_size=$((total_size + file_size))

#increment the file count

file_count=$((file_count + 1))
fi
done

#check if there are any files in the directory


if [ $file_count -eq 0 ]; then
echo "No files found in the directory."
exit 1

36
fi

#calculate the average size


average_size=$((total_size / file_count))

#print the average size


echo "Total number of files : $file_count"
echo "Total size of files : $total_size bytes"
echo "Average file size : $average_size bytes"

output:

./average-size-files.sh /home/sreehary/Documents/java
Total number of files : 27
Total size of files : 35168 bytes
Average file size : 1302 bytes

37
8. A program to create 10 users.
• Use loop structure.
• Get the username from the user.
• Assign same password to all users.

Program:

#!/bin/bash
for((i=0;i<10;i++))
do
echo enter user name
read uname
sudo useradd $uname --password "pass"
done
echo -e “users created successfully”

output:

enter user name


A
enter user name
B
enter user name
C
enter user name
D
enter user name
E
enter user name
F
enter user name
G
enter user name
H
enter user name
I
enter user name
J
“users created successfully”

38
9.A demo program to test different file operators.
• Read filename from the user.
• Check if the file exists then display the contents, otherwise
create the file.
• Check whether the file has read, write and execute
permission.

Program:

#!/bin/bash
# Prompt the user to enter the file name
read -p "Enter the file name: " file_name
# Check if the file exists
if [ ! -e "$file_name" ]; then
# If the file does not exist, create the file
touch "$file_name"
echo "File '$file_name' created successfully."
else
# If the file exists, check if it's empty (size 0)
file_size=$(stat --format="%s" "$file_name")
if [ "$file_size" -eq 0 ]; then
echo "The file '$file_name' is empty."
else
echo "The file '$file_name' is not empty. Size: $file_size bytes."
fi
# Check the file permissions
echo "Checking file permissions for '$file_name':"
if [ -r "$file_name" ]; then
echo "File has read permission."
else
echo "File does not have read permission."
fi
if [ -w "$file_name" ]; then
echo "File has write permission."
else
echo "File does not have write permission."
fi
if [ -x "$file_name" ]; then
echo "File has execute permission."
else
echo "File does not have execute permission."
fi
# Display the contents of the file
echo "Contents of the file '$file_name':"
cat "$file_name"
fi

39
output:

Enter the file name: program6.sh


The file 'program6.sh' is not empty. Size: 624 bytes.
Checking file permissions for 'program6.sh':
File has read permission.
File has write permission.
File has execute permission.
Contents of the file 'program6.sh':
if [ -z "$1" ]
then
echo "Usage: $0 <directory> directory should provided at command line"
exit 1
fi
if [! -d "$1"]
then
echo "The provided path is not a valid directory."
exit 1
fi
total_size=0
file_count=0
for file in "$1"/*
do
if [ -f "$file" ]
then
file_size=$(stat --format="%s" "$file")
total_size=$((total_size + file_size))
file_count=$((file_count + 1))
fi
done
if [ $file_count -eq 0 ]
then
echo "No files found on the directory."
exit 1
fi
average_size=$((total_size/file_count))
echo "Total number of files: $file_count"
echo "Total size of files:$total_size bytes"
echo "Average file size:$average_size bytes"

40
10.write a program with 3 different functions. use menu driven program and invoke function
accordingly.
• Function listing contents of a folder
• Function checking whether a file available in a folder or not if so display the contents.
• Function to check whether a user already member of a group.

Program:

#!/bin/bash
# Function to list the contents of a folder
list_folder_contents() {
read -p "Enter the folder path: " folder_path
# Check if the folder exists
if [ -d "$folder_path" ]; then
echo "Contents of the folder '$folder_path':"
ls -l "$folder_path"
else
echo "The folder '$folder_path' does not exist."
fi
}
# Function to check if a file is available in the folder or not and display the contents
check_file_and_display_contents() {
read -p "Enter the folder path: " folder_path
read -p "Enter the file name: " file_name
# Check if the file exists in the folder
if [ -f "$folder_path/$file_name" ]; then
echo "Contents of the file '$file_name':"
cat "$folder_path/$file_name"
else
echo "The file '$file_name' does not exist in the folder '$folder_path'."
fi
}
# Function to check if a user is already a member of a group
check_user_group_membership() {
read -p "Enter the username: " username
read -p "Enter the group name: " group_name
# Check if the user is a member of the group
if groups "$username" | grep -q "\b$group_name\b"; then
echo "User '$username' is a member of the group '$group_name'."
else
echo "User '$username' is NOT a member of the group '$group_name'."
fi
}
# Menu-driven program
while true; do
echo "Menu:"
echo "1. List contents of a folder"
echo "2. Check if a file exists in a folder and display its contents"
echo "3. Check if a user is a member of a group"
echo "4. Exit"

41
read -p "Enter your choice (1-4): " choice
case $choice in
1)
list_folder_contents
;;
2)
check_file_and_display_contents
;;
3)
check_user_group_membership
;;
4)
echo "Exiting the program."
exit 0
;;
*)
echo "Invalid choice, please try again."
;;
esac
done

output:

Menu:
1. List contents of a folder
2. Check if a file exists in a folder and display its contents
3. Check if a user is a member of a group
4. Exit
Enter your choice (1-4): 1
Enter the folder path: /home/sreehary/Documents/java
Contents of the folder '/home/sreehary/Documents/java':
total 108
-rw-rw-r-- 1 sreehary sreehary 248 Oct 22 21:11 A.class
-rw-rw-r-- 1 sreehary sreehary 823 Oct 22 21:11 B.class
-rw-rw-r-- 1 sreehary sreehary 1649 Nov 10 19:53 better.class
-rw-rw-r-- 1 sreehary sreehary 821 Oct 22 21:11 C.class
-rw-rw-r-- 1 sreehary sreehary 329 Oct 22 21:11 D.class
-rw-rw-r-- 1 sreehary sreehary 332 Oct 21 21:39 D.java
-rw-rw-r-- 1 sreehary sreehary 2179 Nov 30 19:23 Game.class
-rw-rw-r-- 1 sreehary sreehary 1765 Nov 28 21:37 Game.java
-rw-rw-r-- 1 sreehary sreehary 361 Nov 10 19:53 itsdoesNothing.class
-rw-rw-r-- 1 sreehary sreehary 692 Oct 31 22:03 itsdoesNothing.java
-rw-rw-r-- 1 sreehary sreehary 419 Nov 25 12:25 Main.class
-rw-rw-r-- 1 sreehary sreehary 1028 Nov 25 12:25 Main.java
-rw-rw-r-- 1 sreehary sreehary 2103 Nov 25 12:25 Mystring.class
-rw-rw-r-- 1 sreehary sreehary 2782 Jan 7 21:38 MyString.class
-rw-rw-r-- 1 sreehary sreehary 1557 Jan 7 21:38 MyString.java
-rw-rw-r-- 1 sreehary sreehary 1353 Nov 13 15:58 Natural.class
-rw-rw-r-- 1 sreehary sreehary 668 Nov 11 21:34 Natural.java
-rw-rw-r-- 1 sreehary sreehary 1327 Nov 25 11:31 SUM.class

42
-rw-rw-r-- 1 sreehary sreehary 418 Nov 25 11:31 SUM.java
-rw-rw-r-- 1 sreehary sreehary 3576 Jan 1 22:13 TicTacToe.class
-rw-rw-r-- 1 sreehary sreehary 3235 Oct 20 11:32 TicTacToe.java
-rw-rw-r-- 1 sreehary sreehary 336 Nov 15 22:09 use.class
-rw-rw-r-- 1 sreehary sreehary 690 Oct 27 15:21 use.java
-rw-rw-r-- 1 sreehary sreehary 1572 Nov 15 22:09 useless.class
-rw-rw-r-- 1 sreehary sreehary 2401 Nov 5 22:29 Useless.class
-rw-rw-r-- 1 sreehary sreehary 339 Nov 5 22:29 Users.class
-rw-rw-r-- 1 sreehary sreehary 2165 Oct 30 20:24 Users.java
Menu:
1. List contents of a folder
2. Check if a file exists in a folder and display its contents
3. Check if a user is a member of a group
4. Exit
Enter your choice (1-4): 2
Enter the folder path: /home/sreehary/Documents/java
Enter the file name: SUM.java
Contents of the file 'SUM.java':
import java.io.*;
public class SUM
{
public static void main(String args[])
{
DataInputStream br=new DataInputStream(System.in);
String n;
int sum;
try
{
System.out.println("Enter the UpperLimit");
n=br.readLine();
int upperlimit=Integer.parseInt(n);
sum=(upperlimit*(upperlimit+1))/2;
System.out.print("The sum of the "+n+" natural numbers are "+sum);
}catch(Exception e)
{
}
}
}

Menu:
1. List contents of a folder
2. Check if a file exists in a folder and display its contents
3. Check if a user is a member of a group

43
4. Exit
Enter your choice (1-4): 3
Enter the username: sreehary
Enter the group name: sudo
User 'sreehary' is a member of the group 'sudo'.
Menu:
1. List contents of a folder
2. Check if a file exists in a folder and display its contents
3. Check if a user is a member of a group
4. Exit
Enter your choice (1-4): 4
Exiting the program.

44
LINUX ADMINISTRATION

45
1. Linux installation , upgradation ,installation and removal of
packages and installation of peripheral devices (printer)-
installation and configuration.
.Installation of Linux.
1)Installing Any Linux Distribution
2) Boot into the Live CD or Live USB
3) Try out the Linux distribution before installing.
4) Start the installation process.
5) Create a username and password.
6) Set up the partition
7) Boot into Linux
8) Check your hardware
9) Start using Linux
.Installation, upgradation and removal of packages.
▪ Installation of packages:
$ sudo apt install [package name]
▪ Removal of packages:
$ sudo apt remove [package name]
▪ Upgradation of packages:
$ sudo apt upgrade [package name]
.Installation of peripheral devices.
1. Check if driver already exist.
$ dmesg | grep drive_name
2. Add the repository and install.


Add the repository to the repolist, which specified in driver guide.
$ sudo add-apt-repository REPOLIST_OF_DRIVER
Update repository.
$sudo apt-get update

Install package.
$ sudo apt-get install NAME_OF_DRIVER

46
2. Starting and stopping services in run level. The service
command.
.List all services.
$ sudo service --status-all

Starting services.
$ sudo service [service name] start

sudo service cron start

Stopping services
$ sudo service [service name] stop

sudo service cron stop

47
3. Managing process – viewing status, killing, restating etc using ps
command.

View the currently running processes in real time

$ sudo ps

view all currently running processes

$ sudo ps -e

PID TTY TIME CMD


1? 00:00:05 systemd
2? 00:00:00 kthreadd
3? 00:00:00 pool_workqueue_release
4? 00:00:00 kworker/R-rcu_g
5? 00:00:00 kworker/R-rcu_p
6? 00:00:00 kworker/R-slub_
7? 00:00:00 kworker/R-netns
10 ? 00:00:00 kworker/0:0H-events_highpri
12 ? 00:00:00 kworker/R-mm_pe
13 ? 00:00:00 rcu_tasks_kthread
14 ? 00:00:00 rcu_tasks_rude_kthread
15 ? 00:00:00 rcu_tasks_trace_kthread
1294 ? 00:00:00 (sd-pam)

6666 pts/0 00:00:00 sudo


6667 pts/1 00:00:00 sudo
6668 pts/1 00:00:00 ps

kill a process
▪ using kill(process id)
$ sudo kill [option] [PID]

▪ using killall(process name)


$ sudo killall [process_name]

sudo kill -9 1179

48
sudo killall atd

ps -e

PID TTY TIME CMD


1? 00:00:05 systemd
2? 00:00:00 kthreadd
3? 00:00:00 pool_workqueue_release
4? 00:00:00 kworker/R-rcu_g
5? 00:00:00 kworker/R-rcu_p
6? 00:00:00 kworker/R-slub_
7? 00:00:00 kworker/R-netns
10 ? 00:00:00 kworker/0:0H-events_highpri
12 ? 00:00:00 kworker/R-mm_pe
13 ? 00:00:00 rcu_tasks_kthread
14 ? 00:00:00 rcu_tasks_rude_kthread
15 ? 00:00:00 rcu_tasks_trace_kthread
1294 ? 00:00:00 (sd-pam)

6666 pts/0 00:00:00 sudo


6667 pts/1 00:00:00 sudo
6668 pts/1 00:00:00 ps

49
4. Adding and deleting user accounts, changing passwords.

Add user
$ sudo adduser <username>

Delete user
$ sudo userdel <username>

50
5. Changing environmental variables like Path.

View the path

$ echo $PATH

Set the path

$ export PATH=$PATH:/place/with/the/file

51
6. Scheduling job using cron.

.Cron command format


minute hour day month weekday command

. edit crontab file and add commands to be executed

52
7. Mounting and unmounting external file systems.

Detect external hard drive


$ sudo fdisk -l

Create mount point

sudo mkdir /media/usb-drive

Mounting external File System

sudo mount /dev/sdc/media/usb-drive/

53
8. Setting value of mask, changing the permission, changing owner
and groups.

Changing value of umask

Changing permission of owner and groups

54
9. Archiving and backup using tar. Restoring and backup.

.Creating an archive
$ sudo tar <options> [tar-backup-filename] [files-folders-to-be-
backed-up]

Extract tar backup


$ sudo tar <options> [tar_backup_filename]

55
10. Compressing and uncompressing files using any one tool.

.Compressing and decompressing using gzip.

56

You might also like