0% found this document useful (0 votes)
2 views39 pages

Old Linux File

This document is a practical file for Linux commands and shell scripting, submitted by a student of Panjab University for the Master of Computer Applications program. It includes an index of topics covering basic and general commands, wildcards, file permissions, redirection, piping, and various shell scripting exercises. The content provides detailed explanations and examples for each command and script, aimed at enhancing the understanding of Linux operations.
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
0% found this document useful (0 votes)
2 views39 pages

Old Linux File

This document is a practical file for Linux commands and shell scripting, submitted by a student of Panjab University for the Master of Computer Applications program. It includes an index of topics covering basic and general commands, wildcards, file permissions, redirection, piping, and various shell scripting exercises. The content provides detailed explanations and examples for each command and script, aimed at enhancing the understanding of Linux operations.
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

PANJAB UNIVERSITY, CHANDIGARH

Practical File of Linux


Master of Computer Applications (Morning)

SUBMITTED TO:- SUBMITTED BY:-


Dr. R.K. Singla Sir Kuldeep Singh
Roll No: 20
MCA (Sem 1st M)

Department of Computer Science and applications


(DCSA), PU_CHD
Session – 2025-27

INDEX:
1
SR No. Topic Page Remarks
Number
Basic commands: 5
a. pwd
1. b. who
c. whoami
d. who -H
e. who -q
f. cal
g. cal m year
h. date
i. cal year
j. date +%y
k. ls
l. ls -l
m. ls -a
n. ls -al
o. mkdir
p. cd
2. General Commands: 9
a. create a directory
b. create a file [Link]
c. create a file
[Link]
d. display all the files
under the directory
e. create a file name
[Link]
f. copy the contents of
both the files to
[Link]
g. run a shellcript
3. WildCards 11
4. File Grant 13
Permissions
5. Redirection, piping 17
and filters
6. Bash Shell Scripting:
a. Write the shell 23
script to allow the
user to input 5
values and get sum
of numbers using
while loop.

b. Write a shell script 24


to find reverse of
number and find its
sum.

c. Write a shell script


to find greatest and 25
smallest of three 2
numbers.

d. Write shell script to 26


1. Basic commands:
a. pwd
Print Working Directory - shows the current directory you are in.

Output:

b. who
Shows who is currently logged in to the system.
Output:

c. whoami
Displays the current logged-in username.
Output:

d. who -H
Shows logged-in users with a header row describing each column.
Output:

e. who -q
Quick summary showing usernames and the total number of users logged in.
Output:

3
f. cal
Displays the current month calendar.
Output:

g. cal m year
Shows the calendar for a specific month (m) and year.
Output:

h. date
Displays the current date and time.
Output:

i. cal year
Displays the calendar for the entire specified year.

4
Output:

j. date +%y
Shows the last two digits of the current year.
Output:

k. ls
Lists files and directories in the current directory.
Output:

5
l. ls -l
Lists files with detailed information including permissions, owner, size, and
modification date.

Output:

m. ls -a
Lists all files including hidden files (those beginning with a dot).
Output:

n. ls -al
Combines -l and -a to show detailed listing including hidden files.
Output:

o. mkdir
Makes a new directory.
Output:

6
p. cd
Changes the current directory to another directory.
Output:

2. General Commands:
a. Create a directory
The mkdir (make directory) command is used to create a new, empty directory
(folder) within your current location in the filesystem. You can organize your
files and projects by creating separate directories for each.
Output:

b. Create a file [Link]


The touch command quickly creates new, empty files. Here, it is used to create a
file named [Link], which can later be edited to write a shell script or store any
content you want.
Output:

c. Create a file [Link]


You can repeat the touch command to create other files, like [Link].
Output:

d. Display all the files under the directory


7
The ls (list) command displays the names of the files and folders in your current
directory. This helps you quickly see what files and subdirectories exist at your
location.

Output:

e. Create a file named [Link]


Similarly, you can make another empty file named [Link] using touch.
Output:

f. Copy the contents of both the files to [Link]


The cat (concatenate) command is useful for combining and viewing the
contents of files. Here, it joins [Link] and [Link] and writes that combined
output to [Link] (overwriting anything previously in [Link]).
Output:

g. Run a shell script


To run a script file, you must first make it executable, and then you can execute
it directly from the terminal.
First, make it executable:
Output:

8
[Link]
Wildcards in Linux, also known as glob patterns, are special characters that simplify
working with multiple files or directories by matching filenames based on patterns
instead of typing exact names. Using wildcards helps make commands flexible and
powerful by selecting groups of files or directories quickly.
The main wildcard characters are:

1. Asterisk (*)
The most commonly used wildcard, * matches zero or more characters in a
filename or directory. For example, *.txt will match all files ending with .txt in
the current directory, and file* will match any files starting with file, regardless
of what follows. It is helpful when you want to include files with similar name
patterns.
Example
Command Meaning
ls *.txt list all files ending with .txt
ls a* all files starting with a
ls data files containing the word data anywhere
cp *.c backup/ copy all .c programs to backup folder

Output:

9
[Link] Mark (?)
The ? wildcard matches exactly one character in a filename. For
instance, file?.txt would match [Link] or [Link] but not [Link] since the
latter has two characters after file rather than just one. This wildcard is useful for
matching files that differ by one character.
Examples:
Command Meaning
ls ?.txt matches [Link], [Link] but NOT [Link]
ls file?.c matches file1.c, file2.c, but not file10.c
rm data?.py removes [Link], [Link], etc.

Output:

10
[Link] Brackets ([ ]):
Square brackets are used to match any single character within the specified set or
range. For example, file[123].txt matches [Link], [Link], or [Link],
while file[a-c].txt would match files with characters a, b, or c in that position. It
allows matching multiple specific characters or a range within one position.
Examples:
Pattern Matches
ls file[123].txt [Link], [Link], [Link]
ls [ab]* files starting with a or b
ls report[0-9].txt [Link] to [Link]
ls [a-z]*.sh all .sh files starting with a lowercase
letter

Output:

[Link] Grant Permissions:


File permissions in Linux are fundamental to system security and control who can
read, write, or execute a file or directory. These permissions define access rights for
three user categories: the file owner (user), the group the file belongs to, and all other
users (others).
Permissions are represented as:
 r (read): Allows viewing the contents of a file or listing a directory.

11
 w (write): Allows modifying or deleting the file or adding/removing files in a
directory.
 x (execute): Allows running the file as a program or entering a directory.
The chmod (change mode) command is used to grant or modify these permissions
using symbolic or numeric modes.

[Link] mode examples:


 Give the owner execute permission:
Syntax:
chmodu+x filename
 Remove write permission from the group:
Syntax:
chmod g-w filename
 Allow everyone (user, group, others) to read and execute but not write:
Syntax:
chmod a=rx filename
Examples:
[Link] execute permission for user
chmodu+x [Link]

2. Remove write permission from group


chmod g-w project.c
[Link] read & write to others
chmodo+rw [Link]
[Link] exact permissions (overwrite)
chmod u=rwx,g=rx,o=r myfile
[Link] execute permission to everyone
chmoda+x [Link]

Output:

12
[Link] mode:
Permissions can be represented by a three-digit number, each digit representing user,
group, and others permissions respectively:
 4 = read (r)
 2 = write (w)
 1 = execute (x)
 0 = no permission
For example, chmod 755 filename means:
 Owner: 7 (4+2+1 = read, write, execute)
 Group: 5 (4+0+1 = read, execute)
 Others: 5 (4+0+1 = read, execute)
Illustrations:
 Make a script executable only by the owner:
Syntax:

13
chmod 700 [Link]
 Grant read and write to owner, and only read to group and others:
Syntax:
chmod 644 [Link]
 Grant all permissions to everyone (use with caution):
Syntax:
chmod 777 foldername

Examples:
[Link] full permissions (rwx) to owner, group, others
chmod 777 [Link]
[Link]: rwx, Group: r-x, Others: r-x
chmod 755 [Link]
[Link]: rw-, Group: r--, Others: r--
chmod 644 [Link]
[Link]: rwx only
chmod 700 [Link]

Output:

14
[Link] permissions:
Use ls -l to view permissions in symbolic form, e.g.,
text
-rwxr-xr-x 1 user user 234 Nov 21 12:00 [Link]
Here, rwx applies to the owner, r-x to the group, and r-x to others.

15
Output:

[Link], piping and filters


Redirection and piping are powerful ways to control the input and output flows
of commands in Linux, enabling flexible command chaining and data
processing.
[Link] allows you to change the default input/output sources of a
command. Common operators include:
> Redirects the output of a command to a file, overwriting the file.
Syntax:
command > file
>> Redirects the output to a file, appending if the file exists.
Syntax:
command >> file
>>>Redirects input to a command from a file instead of keyboard.
Syntax:
command < file

a) > (Output Redirection – Overwrite)


Sends output to a file and replaces the file content.
ls > [Link]
- Creates/overwrites [Link] with output of ls.
Example:
echo "Hello" > [Link]

16
([Link] now contains only “Hello”)
b) >> (Append Redirection)
Sends output to a file but adds to the end of the file.
echo "New line" >> [Link]
- Adds “New line” at the end
- Does NOT delete previous content
Output:

[Link] (|) passes the output of one command as input to another, allowing
commands to be chained for complex processing.
Syntax:
command1 | command2
Example:
ls | sort
17
-sorts the output of ls
Another example:
cat [Link] | grep "hello"

Output:

[Link] are commands that process input text or data streams. Common filters
include:
 grep — Selects lines matching patterns.
 sort — Sorts lines of text.
 uniq — Removes duplicate lines.
 wc — Counts lines, words, characters.

Example combining all:


cat [Link] | grep "pattern" | sort | uniq> [Link]
This extracts lines containing "pattern", sorts and filters unique lines, then saves them
to [Link].

[Link]
Used to search for text in files.

18
Search for a word:
grep "hello" [Link]
Case-insensitive search:
grep -i "hello" [Link]
Search in all files:
grep "main" *.c

Output:

[Link]
Used to view, create, or combine files.
View file:
cat [Link]
Combine files:
cat file1 file2 > [Link]

19
Add text:
cat >> [Link]

Output:

[Link]
Used to sort lines alphabetically or numerically.
Sort a file:
sort [Link]
Sort in reverse:
sort -r [Link]
Sort numbers:
20
sort -n [Link]

Output:

6. Shell Scripting:
A. Write the shell script to allow the user to input 5 values and get sum of
numbers using while loop.
Program:
#!/bin/bash

count=1
sum=0

while [ $count -le 5 ]


do
read -p "Enter number $count: " num
sum=$((sum + num))

21
count=$((count + 1))
done

echo "Sum of 5 numbers = $sum"

Output:

b. Write a shell script to find reverse of number and find its sum.
Program:
#!/bin/bash
read -p "Enter a number: " n
num=$n
rev=0
sum=0
while [ $n -gt 0 ]
do

22
digit=$(( n % 10 )) # extract last digit
rev=$(( rev * 10 + digit )) # build reverse
sum=$(( sum + digit )) # add digits
n=$(( n / 10 )) # remove last digit
done
echo "Reverse of $num = $rev"
echo "Sum of digits = $sum”

Output:

C. Write a shell script to find greatest and smallest of three numbers.


Program:
#!/bin/bash
read -p "Enter three numbers: " a b c
# Find Greatest
if [ $a -ge $b ] && [ $a -ge $c ]
then
greatest=$a
elif [ $b -ge $a ] && [ $b -ge $c ]
then
greatest=$b
23
else
greatest=$c
fi
# Find Smallest
if [ $a -le $b ] && [ $a -le $c ]
then
smallest=$a
elif [ $b -le $a ] && [ $b -le $c ]
then
smallest=$b
else
smallest=$c
fi
echo "Greatest number = $greatest"
echo "Smallest number= $smallest"

Output:

D. Write shell script to accept users age if greater than 18 then eligible to
vote otherwise not.
Program:

#!/bin/bash

read -p "Enter your age: " age

if [ $age -ge 18 ]
then
echo "You are eligible."
else

24
echo "You are NOT eligible."
fi

Output:

25
E. Write shell script to create, view, and delete files using a menu-driven.
#!/bin/bash
while true
do
echo "---- MENU ----"
echo "1. Create File"
echo "2. View File"
echo "3. Delete File"
echo "4. Exit"
read -p "Enter your choice: " ch
case $ch in
1) read -p "Enter filename: " f
touch "$f"
echo "File created."
;;
2) read -p "Enter filename: " f
if [ -f "$f" ]; then
cat "$f"
else
echo "File not found."
fi
;;
3) read -p "Enter filename: " f
rm -i "$f"
;;
4) exit ;;
*) echo "Invalid choice." ;;
esac
done

OUTPUT:

26
F. Write shell script to read n numbers Into an array & find maximum +
minimum.
Program:

#!/bin/bash

read -p "Enter how many numbers: " n

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


do
read -p "Enter number $((i+1)): " arr[i]
done

max=${arr[0]}
min=${arr[0]}

for num in "${arr[@]}"


do
if (( num > max )); then max=$num; fi
if (( num < min )); then min=$num; fi
done

echo "Maximum = $max"


echo "Minimum = $min"

OUTPUT:

27
G. Write shell script to print pattern using nested loops:
*
***
*****
*******
*********
Program:

#!/bin/bash

read -p "Enter number of rows: " n

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


do
for (( s=n; s>i; s-- ))
do
echo -n " "
done

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


do
echo -n "*"
done

echo
done

OUTPUT:

28
H. Write shell script to count number of words, lines, and characters in
a file.
Program:

#!/bin/bash

read -p "Enter filename: " f

if [ -f "$f" ]
then
lines=$(wc -l < "$f")
words=$(wc -w < "$f")
chars=$(wc -c < "$f")

echo "Lines: $lines"


echo "Words: $words"
echo "Characters: $chars"
else
echo "File not found!"
fi

OUTPUT:

29
I. Write shell script to find prime numbers between two limits.
Program:

#!/bin/bash

read -p "Enter start limit: " a


read -p "Enter end limit: " b

echo "Prime numbers are:"

for (( num=a; num<=b; num++ ))


do
if [ $num -lt 2 ]; then continue; fi

prime=1
for (( i=2; i*i<=num; i++ ))
do
if (( num % i == 0 )); then
prime=0
break
fi
done

if (( prime == 1 )); then


echo -n "$num "
fi
done
echo

OUTPUT:

30
J. Write shell script to show various system configuration like
i) currently logged user and his logged name
ii) your current shell
iii) your home directory
iv) your operating system type
v) your current path setting
vi) current working directory
vii)show currently logged number of users
viii) exit

Program:

#!/bin/bash
echo "---- System Configuration ----"

# i) Currently logged user and his logged name


echo "Logged User: $(whoami)"
echo "Login Name: $LOGNAME"

# ii) Your current shell


echo "Current Shell: $SHELL"

# iii) Your home directory


echo "Home Directory: $HOME"

# iv) Your operating system type


echo "Operating System Type: $(uname)"

31
# v) Your current path setting
echo "Path Setting: $PATH"

# vi) Current working directory


echo "Current Working Directory: $(pwd)"

# vii) Show currently logged number of users


echo "Number of Logged-in Users: $(who | wc -l)"

# viii) Exit
echo "Exiting..."
exit

Output:

32
7. C Shell Scripting:
A. Write a program to count vowels & consonants in a string.
#include <stdio.h>

int main() {

char s[100];

int i, v=0, c=0;

printf("Enter a string: ");

gets(s);

for(i=0; s[i]; i++) {

if(s[i]=='A'||s[i]=='E'||s[i]=='I'||s[i]=='O'||s[i]=='U'||

s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u')

v++;

else if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z'))

c++;

printf("Vowels = %d\nConsonants = %d\n", v, c);

OUTPUT:

33
B. Write a program for matrix multiplication.
#include <stdio.h>
int main() {
int a[2][2]={{1,2},{3,4}}, b[2][2]={{2,0},{1,2}}, c[2][2], i,j;

for(i=0;i<2;i++)
for(j=0;j<2;j++)
c[i][j]=a[i][0]*b[0][j] + a[i][1]*b[1][j];

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

OUTPUT:

34
C. Write a program for check prime using function.
#include <stdio.h>

int isPrime(int n){


for(int i=2;i*i<=n;i++)
if(n%i==0) return 0;
return 1;
}
int main(){
int n;
scanf("%d",&n);
if(isPrime(n)) printf("Prime");
else printf("Not Prime");
}

OUTPUT:

35
D. Write a program for swap two numbers without temporary variable.
#include <stdio.h>

int main(){

int a=5, b=9;

a = a + b;

b = a - b;

a = a - b;

printf("a=%d b=%d\n",a,b);

OUTPUT:

36
E. Write a program for reverse a string without strrev().
#include <stdio.h>
#include <string.h>

int main() {
char s[50];
int i, n;

printf("Enter string: ");


gets(s);

n = strlen(s);
for(i = n-1; i >= 0; i--)
printf("%c", s[i]);

return 0;
}

OUTPUT:

37
F. Write a program for binary search in an array (array must be
sorted).
#include <stdio.h>
int main() {
int a[] = {2, 5, 9, 14, 20, 33};
int n = 6, key, low = 0, high = n-1, mid;

printf("Enter element to search: ");


scanf("%d", &key);

while(low <= high) {


mid = (low + high) / 2;
if(a[mid] == key) {
printf("Found at index %d\n", mid);
return 0;
}
else if(key < a[mid])
high = mid - 1;
else
low = mid + 1;
}
printf("Not found\n");
}

OUTPUT:

38
G. Write a program for selection sort in an array.
#include <stdio.h>

int main() {
int a[] = {29, 10, 14, 37, 13};
int n = 5, i, j, min, temp;

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


min = i;
for(j = i+1; j < n; j++)
if(a[j] < a[min])
min = j;

temp = a[i];
a[i] = a[min];
a[min] = temp;
}

printf("Sorted Array: ");


for(i = 0; i < n; i++)
printf("%d ", a[i]);
}

OUTPUT:

39

You might also like