Docsity

linux file pdf page 1, Study Guides, Projects, Research of Linux skills

Toggle sidebar
bg1
TYBCA – DIV A - BCA24165 Linux
Dudhat Kirti M. Page 1
1) Write a shell script to find all prime numbers in given
range.
Program:-
#!/bin/bash
# Prompt user for range
read -p "Enter the starting number: " start
read -p "Enter the ending number: " end
# Ensure valid input range
if [ "$start" -lt 2 ]; then
start=2
fi
echo "Prime numbers between $start and $end:"
for (( num=start; num<=end; num++ )); do
is_prime=1
# Check divisors up to square root of num
for (( i=2; i*i<=num; i++ )); do
if [ $((num % i)) -eq 0 ]; then
is_prime=0
break
fi
done
if [ $is_prime -eq 1 ]; then
echo -n "$num "
fi
done
echo "" # Newline at the end#!/bin/bash
# Prompt user for range
read -p "Enter the starting number: " start
read -p "Enter the ending number: " end
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b

Partial preview of the text

Download linux file pdf page 1 and more Study Guides, Projects, Research Linux skills in PDF only on Docsity!

1) Write a shell script to find all prime numbers in given

range.

Program:- #!/bin/bash

Prompt user for range

read - p "Enter the starting number: " start read - p "Enter the ending number: " end

Ensure valid input range

if [ "$start" - lt 2 ]; then start= fi echo "Prime numbers between $start and $end:" for (( num=start; num<=end; num++ )); do is_prime=

Check divisors up to square root of num

for (( i=2; i*i<=num; i++ )); do if [ $((num % i)) - eq 0 ]; then is_prime= break fi done if [ $is_prime - eq 1 ]; then echo - n "$num " fi done echo "" # Newline at the end#!/bin/bash

Prompt user for range

read - p "Enter the starting number: " start read - p "Enter the ending number: " end

Ensure valid input range

if [ "$start" - lt 2 ]; then start= fi echo "Prime numbers between $start and $end:" for (( num=start; num<=end; num++ )); do is_prime=

Check divisors up to square root of num

for (( i=2; i*i<=num; i++ )); do if [ $((num % i)) - eq 0 ]; then is_prime= break fi done if [ $is_prime - eq 1 ]; then echo - n "$num " fi done echo "" # Newline at the end OUTPUT:-

Program:- #!/bin/bash

Prompt user for input

read - p "Enter a single character: " input

Validate if user entered exactly one character

if [ ${#input} - ne 1 ]; then echo "Error: Please enter exactly ONE character." exit 1 fi

Check character type using regex matching

if [[ "$input" =~ [[:alpha:]] ]]; then echo "'$input' is an Alphabet." elif [[ "$input" =~ [[:digit:]] ]]; then echo "'$input' is a Digit." else echo "'$input' is a Special Character." Fi OUTPUT:-

4) Write a shell script to find sum of digits of a number.

shumof

Program:- #!/bin/bash

Prompt user for input

read - p "Enter a number: " num

Remove negative sign if the user inputs a negative number

num=${num#-}

Validate that the input is a valid non-negative integer

if! [[ "$num" =~ ^[0-9]+$ ]]; then echo "Error: Please enter a valid whole number." exit 1 fi sum= temp=$num

Extract digits one by one using modulo

while [ $temp - gt 0 ]; do digit=$((temp % 10)) sum=$((sum + digit)) temp=$((temp / 10)) done echo "Sum of digits of $num is: $sum" OUTPUT:-

5) Write a shell script to print fibonacci series upto entered

value N.

Program:- #!/bin/bash

Prompt user for the upper limit

read - p "Enter the maximum value (N): " N

Validate input

if! [[ "$N" =~ ^[0-9]+$ ]]; then echo "Error: Please enter a valid non-negative integer." fn=$((a + b)) a=$b b=$fn done

Reverse the number mathematically

while [ $temp - gt 0 ]; do remainder=$((temp % 10)) reverse=$((reverse * 10 + remainder)) temp=$((temp / 10)) done

Check if the original number matches the reversed number

if [ $num - eq $reverse ]; then echo "$num is a Palindrome." else echo "$num is NOT a Palindrome." fi OUTPUT:-

8) Write a menu driven shell script to create and delete a file

which will accept two command line arguments (file name

and create / delete option).

Program:- #!/bin/bash

Function to display usage/help

usage() { echo "Usage: $0 " echo "Example: $0 test.txt create" echo " $0 test.txt delete" }

Function to create a file

create_file() { local file="$1" if [ - z "$file" ]; then read - p "Enter filename to create: " file fi if [ - z "$file" ]; then echo "[-] Error: Filename cannot be empty." return 1 fi if [ - e "$file" ]; then echo "[!] Warning: File '$file' already exists." else touch "$file"

if [ $? - eq 0 ]; then echo "[+] Success: File '$file' created successfully." else echo "[-] Error: Failed to create file '$file'." fi fi }

Function to delete a file

delete_file() { local file="$1" if [ - z "$file" ]; then read - p "Enter filename to delete: " file fi if [ - z "$file" ]; then echo "[-] Error: Filename cannot be empty." return 1 fi if [ - e "$file" ]; then rm - i "$file" if [! - e "$file" ]; then echo "[+] Success: File '$file' deleted." else echo "[!] Deletion canceled or failed." fi else echo "[-] Error: File '$file' does not exist." fi }

Interactive Menu Function

show_menu() { local target_file="$1" while true; do echo "=================================" echo " FILE MANAGER MENU " echo "=================================" echo "Target File: ${target_file:-"(None specified)"}" echo "1. Create File" echo "2. Delete File" echo "3. Exit" echo "=================================" read - p "Select an option [1-3]: " choice case $choice in

  1. create_file "$target_file" ;;

9) Write a shell script to count length of string and reverse a

string.

Program:- #!/bin/bash

==========================================================

Script Name : string_ops.sh

Description : Count length and reverse a string in Kali Linux

==========================================================

Color declarations for output formatting (supported in Kali Terminal)

GREEN='\033[0;32m' CYAN='\033[0;36m' RED='\033[0;31m' NC='\033[0m' # No Color

Check if string was provided as an argument, otherwise prompt the user

if [ - n "$1" ]; then input_str="$1" else echo - e "${CYAN}[*] Input string not provided as an argument.${NC}"

read - p "Enter string: " input_str fi

Validation: Check if string is empty

if [ - z "$input_str" ]; then echo - e "${RED}[-] Error: String cannot be empty.${NC}" exit 1 fi

1. Calculate length using native Bash syntax ${#var}

str_length=${#input_str}

2. Reverse string using standard Linux utility 'rev'

reversed_str=$(echo "$input_str" | rev)

Display Results

echo "" echo - e "${CYAN}========== STRING ANALYSIS ==========${NC}" echo - e "Original String : ${GREEN}$input_str${NC}" echo - e "String Length : ${GREEN}$str_length${NC} characters" echo - e "Reversed String : ${GREEN}$reversed_str${NC}" echo - e "${CYAN}=====================================${NC}" OUTPUT:-

10 ) Write a shell script to count number of digits, vowels

and constants.

Program:-

echo "Digits : $digits" echo "Vowels : $vowels" echo "Consonants : $consonants" echo "=====================================" OUTPUT:-

11) Write a shell script Which works like calculator and

performs below operations Addition, Subtract ,Division

,Multiplication.

Program:- #!/bin/bash

==========================================================

Script Name : calculator.sh

Description : Interactive calculator script for basic arithmetic operations

==========================================================

Color formatting

CYAN='\033[0;36m' GREEN='\033[0;32m' RED='\033[0;31m' NC='\033[0m' # No Color

Helper function to read a valid number

read_number() { local prompt_msg="$1"

local var_name="$2" while true; do read - p "$prompt_msg" num

Regex check for integers or decimals (including negative values)

if [[ "$num" =~ ^-?[0-9]+(.[0-9]+)?$ ]]; then eval "$var_name='$num'" break else echo - e "${RED}[-] Invalid input. Please enter a valid number.${NC}" fi done } while true; do echo "" echo - e "${CYAN}=====================================${NC}" echo - e "${CYAN} MENU CALCULATOR ${NC}" echo - e "${CYAN}=====================================${NC}" echo "1. Addition (+)" echo "2. Subtraction (-)" echo "3. Multiplication (*)" echo "4. Division (/)" echo "5. Exit" echo - e "${CYAN}=====================================${NC}" read - p "Select an option [1-5]: " choice case $choice in

read_number "Enter first number: " num read_number "Enter second number: " num result=$(echo "scale=2; $num1 + $num2" | bc) echo - e "${GREEN}[+] Result: $num1 + $num2 = $result${NC}" ;;

read_number "Enter first number: " num read_number "Enter second number: " num result=$(echo "scale=2; $num1 - $num2" | bc) echo - e "${GREEN}[+] Result: $num1 - $num2 = $result${NC}" ;;

read_number "Enter first number: " num read_number "Enter second number: " num result=$(echo "scale=2; $num1 * $num2" | bc) echo - e "${GREEN}[+] Result: $num1 * $num2 = $result${NC}" ;;

Script Name : swap_case.sh

Description : Invert letter cases (Upper - > Lower, Lower - > Upper)

==========================================================

Get input from command-line argument or prompt user

if [ - n "$1" ]; then input_str="$1" else read - p "Enter a string: " input_str fi

Validation: Check if input string is empty

if [ - z "$input_str" ]; then echo "[-] Error: Input string cannot be empty." exit 1 fi

Swap upper and lower case characters using standard 'tr' utility

swapped_str=$(echo "$input_str" | tr 'a-zA-Z' 'A-Za-z')

Display output

echo "=====================================" echo "Original String : $input_str" echo "Swapped Case : $swapped_str" echo "=====================================" OUTPUT:-

13) Write a shell script to scans the name of the command

and executes it.

Program:- #!/bin/bash

==========================================================

Script Name : command_runner.sh

Description : Prompts for a shell command and executes it

==========================================================

Color formatting

CYAN='\033[0;36m' GREEN='\033[0;32m' RED='\033[0;31m' NC='\033[0m' # No Color echo - e "${CYAN}=====================================${NC}" echo - e "${CYAN} COMMAND RUNNER SHELL ${NC}" echo - e "${CYAN} Type 'exit' or 'quit' to close ${NC}" echo - e "${CYAN}=====================================${NC}" while true; do

Display prompt and scan user input

echo "" read - p "Enter command to execute: " user_cmd

1. Check for exit commands

if [[ "$user_cmd" == "exit" || "$user_cmd" == "quit" ]]; then echo "Exiting command runner. Goodbye!" break fi

2. Check for empty input

if [ - z "$user_cmd" ]; then echo - e "${RED}[-] Warning: No command entered.${NC}" continue fi

3. Extract base command name to check existence

base_cmd=$(echo "$user_cmd" | awk '{print $1}')

Check if command exists in system PATH or built-in

if command - v "$base_cmd" > /dev/null 2>&1; then echo - e "${GREEN}[+] Executing: $user_cmd${NC}" echo "-------------------------------------"

Execute the scanned command

eval "$user_cmd"

Capture and display execution exit status

exit_code=$? echo "-------------------------------------" if [ $exit_code - eq 0 ]; then echo - e "${GREEN}[+] Command completed successfully.${NC}" else echo - e "${RED}[!] Command exited with status code $exit_code.${NC}"

echo " Reading File: $filepath" echo "==================================================" line_number=

IFS= prevents leading/trailing whitespace from being trimmed

- r prevents backslash escapes from being interpreted

while IFS= read - r line || [ - n "$line" ]; do echo "Line $line_number: $line" ((line_number++)) done < "$filepath" echo "==================================================" echo " Finished reading $((line_number - 1)) line(s)." echo "==================================================" OUTPUT:-

15) Write a shell script to find the largest among the 3 given

numbers.

Program:- #!/bin/bash

==========================================================

Script Name : find_largest.sh

Description : Finds the largest number among three given numbers

==========================================================

Check if 3 arguments are passed, otherwise ask interactively

if [ $# - eq 3 ]; then num1="$1" num2="$2" num3="$3" else echo "Please enter 3 numbers:"

read - p "Number 1: " num read - p "Number 2: " num read - p "Number 3: " num fi

Input Validation: Ensure all inputs are valid integers or decimals

for num in "$num1" "$num2" "$num3"; do if! [[ "$num" =~ ^-?[0-9]+(.[0-9]+)?$ ]]; then echo "[-] Error: '$num' is not a valid number." exit 1 fi done

Compare numbers using 'bc' to support both integers and floating-point decimals

if (( $(echo "$num1 >= $num2" | bc - l) )) && (( $(echo "$num1 >= $num3" | bc - l) )); then largest="$num1" elif (( $(echo "$num2 >= $num1" | bc - l) )) && (( $(echo "$num2 >= $num3" | bc

  • l) )); then largest="$num2" else largest="$num3" fi

Display result

echo "=================================" echo "Numbers : $num1, $num2, $num3" echo "Largest : $largest" echo "=================================" OUTPUT:-