unix
unix
a)Write a shell script to perform arithmetic operations (+, -, *, /) based on user input (choose
operation).
#!/bin/bash
# User input
echo "Enter rst number: "
read num1
echo "Enter an operation (+, -, *, /): "
read op
echo "Enter second number: "
read num2
# Perform calculation
case $op in
+)
result=$(( num1 + num2 ))
;;
-)
result=$(( num1 - num2 ))
;;
\*)
result=$(( num1 * num2 ))
;;
/)
if (( num2 == 0 )); then
echo "Error: Division by zero is not allowed"
exit 1
echo : This command prints a message to the terminal asking the user for input.
read : This command captures the user's input and stores it in the speci ed variable (num1, op, or
num2).
num1: Stores the rst number entered by the user.
op: Stores the arithmetic operation (+, -, *, /) entered by the user.
num2: Stores the second number entered by the user.
b)Write a shell script that nds the largest and smallest element in an array.
• The -a option in the read command is used to read input into an array in Bash
• Ex: read -a arr.
This command reads a line of space-separated numbers from the user and stores them in an
array named arr.
• Each element in the input gets assigned to an index in the array (e.g., arr[0], arr[1], etc.).
#!/bin/bash
fi
fi
fi
fl
fi
fi
# Read array from user
echo "Enter numbers separated by space: "
read -a arr
done
2
a)Write a shell script to convert temperature from Celsius to Fahrenheit and vice versa.
#!/bin/bash
;;
2)
echo -n "Enter temperature in Fahrenheit: "
read fahrenheit
# Check if input is numeric
if [[ $fahrenheit =~ ^-?[0-9]+([.][0-9]+)?$ ]]; then
fahrenheit_to_celsius $fahrenheit
else
echo "Invalid input. Please enter a numeric value."
;;
3)
echo "Exiting the program."
exit 0
;;
*)
echo "Invalid choice, please select 1, 2, or 3."
;;
esac
b)Write a C program that uses a pipe to pass a string from a parent process to a child
process.
Explanation:
1. Pipe Creation:
o The pipe() system call creates a pipe. It returns two le descriptors:
▪ pipe_fd[0]: For reading.
▪ pipe_fd[1]: For writing.
2. Fork:
o fork() creates a new child process. The child process inherits the parent's le
descriptors.
3. Parent Process:
o Closes the read end of the pipe (pipe_fd[0]).
o Writes a string to the pipe using write().
4. Child Process:
o Closes the write end of the pipe (pipe_fd[1]).
o Reads the string from the pipe using read() and prints it.
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
fi
fi
fi
fi
#de ne BUFFER_SIZE 100
int main() {
int pipe_fd[2]; // File descriptors for the pipe
pid_t pid; // Process ID returned by fork()
char write_msg[] = "Hello from parent process!"; // Message to be written
char read_msg[BUFFER_SIZE]; // Bu er to store the read message
if (pid > 0) {
// Parent process
close(pipe_fd[0]); // Close the read end of the pipe (not needed by parent)
return 0;
}
3
a)Write a shell script that takes a lename as input and checks if the le exists. If the le
exists,
print the content of the le
[ -f "$ lename" ]:
The -f ag checks if the given lename corresponds to a regular le.
If the le exists, the condition evaluates to true, and the script proceeds to the next block.
#!/bin/bash
# Check if le exists
if [ -f "$ lename" ]; then
echo "File exists. Contents of the le:"
cat "$ lename"
else
echo "Error: File does not exist."
b)Write a C program to calculate and display the area of the circle in the child’s process and
the nd
the area of a square in the parent process.
void calculateCircleArea( oat radius);: Declares a function to calculate the area of a circle.
void calculateSquareArea( oat side);: Declares a function to calculate the area of a square.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#de ne PI 3.14159
// Function prototypes
void calculateCircleArea( oat radius);
void calculateSquareArea( oat side);
int main() {
pid_t pid;
oat radius, side;
if (pid < 0) {
// Fork failed
perror("Fork failed");
exit(1);
} else if (pid == 0) {
// Child process
calculateCircleArea(radius);
exit(0); // Exit child process
} else {
// Parent process
wait(NULL); // Wait for child process to nish
calculateSquareArea(side);
}
return 0;
fi
fl
fi
fi
fi
fi
fi
fi
fl
fl
fl
fl
fi
fi
}
4
a)Create a shell script that reads the content of a le and counts the number of lines, words
and
number of characters in the le.
#!/bin/bash
b)Write a C program to simulate a basic scheduler that executes tasks in First come rst
Serve.
#include <stdio.h>
int main() {
int n, i, j;
int bt[20], at[20], wt[20], tat[20], ct[20];
oat avwt = 0, avtat = 0;
// Calculate and display average waiting time and average turnaround time
avwt /= n; // Average waiting time
avtat /= n; // Average turnaround time
return 0;
}
5
a)Write a script that searches for all les in a present working directory and sorts them by
size, displaying
the largest le rst.
#!/bin/bash
# Find all les in the directory and its subdirectories, calculate their sizes,
# sort them by size in descending order, and display the top 10 largest les.
nd "$directory" -type f -exec du -h {} + | sort -rh | head -n 10
fi
fi
fi
fi
fi
fi
Explanation:
• nd "$directory" -type f:
nd: This command is used to search for les and directories.
"$directory": The search starts in the speci ed directory (stored in the $directory variable). -
type f: This option tells nd to search for les only (not directories). It will match only regular
les.
• -exec du -h {} +:
-exec: This option tells nd to execute a command on each le found.
du -h: The du command (disk usage) is used to show the disk space used by les and
directories.
-h: This makes the output human-readable (e.g., 1K, 2M, 3G), so the le sizes are displayed
in a more understandable format (KB, MB, GB).
{}: This is a placeholder that gets replaced by the current le found by nd. For each le, nd
runs the command du -h and passes the le as an argument to du.
+: The + after {} is used to group multiple les together into a single du command. It improves
performance by running du on multiple les at once, instead of running it separately for each
le.
Without +, the -exec command would execute du -h for every individual le, which is less
e cient.
With +, all the les are passed to du in a single call.
• | sort -rh:
|: This is the pipe operator, which takes the output of the command on the left ( nd ... -exec
du -h {}) and passes it as input to the command on the right (sort -rh).
sort -rh:
sort: The sort command arranges the lines of input in a speci ed order.
-r: This option sorts the les in reverse order, meaning the largest les will appear rst.
-h: This option ensures the sorting works on human-readable sizes (like 1K, 2M, 3G) correctly.
Without this, sort would treat the le sizes as plain text and not in a meaningful way.
• | head -n 10:
head: The head command limits the output to the rst N lines.
-n 10: This option limits the output to the top 10 lines. In this case, it will show the top 10
largest les by size.
b)Write a shell script that computes the gross salary of an employee according to the
following
rules
i) If basic salary is < 1500 then HRA =10% of the basic and DA =90% of the basic.
ii) If basic salary is >=1500 then HRA =Rs500 and DA=98% of the basic
The basic salary is entered interactively through the key board.
#!/bin/bash
6
a)Write a C program that appends a string to an existing le. Read the le name and text as
command
line arguments
#!/bin/bash
# Extract arguments
lename="$1"
text="$2"
#include <stdio.h>
int main() {
// Initialize variables
int i, NOP, sum = 0, count = 0, y, quant;
int wt = 0, tat = 0, at[10], bt[10], temp[10];
oat avg_wt, avg_tat;
return 0;
}
fl
fl
fi
fi
7
a)Create a shell script that implements a basic calculator (addition, subtraction,
multiplication, division)
using a case statement.
#!/bin/bash
# Extract arguments
num1=$1
operator=$2
num2=$3
#!/bin/bash
# Change le permissions
chmod "$permissions" "$ lename" 2>/dev/null
if [ $? -ne 0 ]; then
echo "Error: Invalid permissions '$permissions'. Please enter valid permissions."
exit 1
The command to change le or directory permissions in Linux and Unix systems is chmod
chmod [OPTIONS] MODE FILE
MODE can be numeric (e.g., 755) or symbolic (e.g., u+rwx).
FILE is the target le or directory.
Example: chmod 755 lename
Owner: read, write, execute (7)
8a)Write a shell script to print Fibonacci numbers up to n (user input) using a while loop.
#!/bin/bash
# Validate input
if ! [[ "$n" =~ ^[0-9]+$ ]]; then
echo "Error: Please enter a positive integer."
exit 1
count=0
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
while [ $count -lt $n ]
do
echo -n "$a " # Print current Fibonacci number
fn=$((a + b)) # Compute next number
a=$b # Shift values
b=$fn
count=$((count + 1))
done
#include <stdio.h>
int main() {
// Initialize variables
int i, NOP, sum = 0, count = 0, y, quant;
int wt = 0, tat = 0, at[10], bt[10], temp[10];
oat avg_wt, avg_tat;
return 0;
}
9
a)Write a shell script to display the current date, time, and the user's home directory.
#!/bin/bash
# Completion message
echo "Script execution completed."
b)Write a C program to simulate a basic scheduler that executes tasks in First come rst
Serve.
#include <stdio.h>
int main() {
int n, i, j;
int bt[20], at[20], wt[20], tat[20], ct[20];
oat avwt = 0, avtat = 0;
// Calculate and display average waiting time and average turnaround time
avwt /= n; // Average waiting time
avtat /= n; // Average turnaround time
return 0;
}
fl
fi
10
a)Write a shell script that calculates the factorial of a number entered by the user.
#!/bin/bash
# Initialize factorial to 1
fact=1
b)Write a shell script that searches for a speci c word in a le and displays the matching
lines using
#!/bin/bash
# Check if le exists
if [ ! -f "$ lename" ]; then
echo "Error: File '$ lename' not found!"
exit 1
11
a)Write a Shell Script to Check Whether a Given Number is Prime
#!/bin/bash
done
# Display result
if [ "$is_prime" -eq 1 ]; then
echo "$num is a prime number."
else
echo "$num is not a prime number."
b)Write a bash script that displays the top 15 processes based on CPU usage. The script
should
provide the following options to the user:
• Show processes for a speci c user (user input required).
• Sort and display processes by memory usage
#!/bin/bash
;;
2)
echo "Top processes sorted by memory usage:"
ps -eo pid,user,%cpu,%mem,comm --sort=-%mem | head -15
;;
3)
echo "Exiting..."
break
;;
*)
echo "Invalid choice! Please try again."
;;
esac