Q1. Write a shell script using grep command to print prime numbers between 1 to 30.

Problem Explanation

This script uses grep with pattern matching to identify and display prime numbers between 1 and 30. Prime numbers have no divisors except 1 and themselves.

Step-By-Step Instructions

  • Create a list of numbers 1 to 30
  • Use grep with regex patterns to match primes
  • Filter non-primes using grep -v
  • Display prime numbers

Code

Bash Shell
#!/bin/bash
echo "Prime numbers between 1 to 30:"

for i in {1..30}
do
    is_prime=1
    for j in {2..$((i-1))}
    do
        if [ $((i % j)) -eq 0 ]; then
            is_prime=0
            break
        fi
    done
    
    if [ $i -gt 1 ] && [ $is_prime -eq 1 ]; then
        echo $i
    fi
done

Output

Expected Output:
2 3 5 7 11 13 17 19 23 29

Key Concept

Prime number detection uses divisibility testing. Nested loops check all potential divisors. break exits inner loop early. modulo operator determines divisibility.

Q2. Write a shell script that check given input is a valid email id.

Problem Explanation

This script validates email format using regular expressions. Valid email has username@domain.extension format with proper characters.

Code

Bash Shell
#!/bin/bash
read -p "Enter email: " email

if [[ $email =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
    echo "$email is a valid email"
else
    echo "$email is not a valid email"
fi

Output

Expected Output:
Input: user@example.com Output: user@example.com is a valid email Input: invalid.email Output: invalid.email is not a valid email

Key Concept

[[ ]] enables extended regex. =~ matches patterns. Character classes [a-zA-Z0-9] match allowed characters. This demonstrates important email validation regex patterns.

Q3. Write a shell script to find whether the supplied user working on network or not. If he / she is working then display his / her login time.

Problem Explanation

This script checks if a user is currently logged in using the w or who command, and displays their login time if they are online.

Code Example

Bash Shell
#!/bin/bash
read -p "Enter username: " user

if who | grep -q $user; then
    echo "$user is working on network"
    who | grep $user
else
    echo "$user is not working on network"
fi

Key Concept

who command lists logged-in users. grep -q suppresses output and sets exit status. Pipes chain commands. This demonstrates system user monitoring.

Q4. Write a shell script which accepts a file name as a input. Find out whether it is ordinary file or directory.

Problem Explanation

This script determines whether the input path is a regular file, directory, or neither, and displays appropriate file permissions if it exists.

Code Example

Bash Shell
#!/bin/bash
read -p "Enter path: " path

if [ -f "$path" ]; then
    echo "$path is a regular file"
    echo "Permissions:"
    ls -l "$path"
elif [ -d "$path" ]; then
    echo "$path is a directory"
else
    echo "$path does not exist"
fi

Key Concept

Test operators -f and -d distinguish file types. ls -l displays detailed permissions. This is essential for file system navigation and security verification.

Q5. Write a shell script which copies files from one directory to another during copy command.

Problem Explanation

This script copies all files from a source directory to a destination directory with error handling and verification.

Code Example

Bash Shell
#!/bin/bash
read -p "Enter source directory: " src
read -p "Enter destination directory: " dest

if [ ! -d "$src" ]; then
    echo "Source directory does not exist"
    exit 1
fi

cp -r "$src"/* "$dest"/ && echo "Files copied successfully"

Key Concept

cp -r copies recursively (files and directories). && executes only if previous command succeeds. Error checking prevents data loss.

Q6. Create a data file which contains given format and perform the given operations on that data file using sed.

Problem Explanation

This script uses sed (Stream Editor) to perform text transformations like substitution, deletion, and pattern matching on data files.

Code Example

Bash Shell
#!/bin/bash
# Create data file
echo "John:25000:Science
Jane:30000:Arts
Mike:35000:Commerce" > data.txt

# Substitute text
sed 's/John/Johnny/g' data.txt

# Delete lines matching pattern
sed '/Arts/d' data.txt

# Print specific lines
sed -n '1,2p' data.txt

Key Concept

sed 's/pattern/replacement/g' substitutes all occurrences. /d deletes lines. -n and p print specific lines. sed is powerful for batch text processing.

Q7. Write a shell script to copy a file using command line argument, source file must be exists and readable and target file must be non existing file name.

Problem Explanation

This script copies files with comprehensive validation: source must exist and be readable, destination must not exist to prevent overwriting.

Code Example

Bash Shell
#!/bin/bash

if [ $# -ne 2 ]; then echo "Usage: $0 source dest"; exit 1; fi
if [ ! -f "$1" ] || [ ! -r "$1" ]; then echo "Source not readable"; exit 1; fi
if [ -e "$2" ]; then echo "Destination exists"; exit 1; fi

cp "$1" "$2" && echo "Copied successfully"

Key Concept

-r tests readability. -e tests existence. || chains error conditions. This demonstrates defensive programming in file operations.

Q8. Write a shell script, which works similar to wc command accept filename as command line argument.

Problem Explanation

This script replicates wc (word count) command functionality: counts lines, words, and characters in a file.

Code Example

Bash Shell
#!/bin/bash

lines=$(wc -l < "$1")
words=$(wc -w < "$1")
chars=$(wc -c < "$1")

echo "Lines: $lines"
echo "Words: $words"
echo "Characters: $chars"

Key Concept

wc -l/w/c count lines/words/characters. < redirects file to stdin. Command substitution $() captures output. This demonstrates file content analysis.

Q9. Accept any word through command line argument and find out its length.

Problem Explanation

This simple script calculates the length of a word passed as a command-line argument using the ${#variable} syntax.

Code Example

Bash Shell
#!/bin/bash
if [ $# -eq 0 ]; then
    echo "Usage: $0 word"
    exit 1
fi

word="$1"
length=${#word}
echo "Length of '$word' is $length"

Key Concept

${#var} returns string length. $# checks argument count. This demonstrates string manipulation in shell scripting.

Q10. Write a shell script, which sort an array of integers in ascending order.

Problem Explanation

This script sorts an array of integers in ascending order using shell loops and comparison operators or by using the sort command.

Code Example

Bash Shell
#!/bin/bash
read -p "Enter numbers separated by space: " -a arr

# Bubble sort
for ((i=0; i<${#arr[@]}; i++))
do
    for ((j=i+1; j<${#arr[@]}; j++))
    do
        if [ ${arr[i]} -gt ${arr[j]} ]; then
            temp=${arr[i]};
            arr[i]=${arr[j]};
            arr[j]=$temp;
        fi
    done
done

echo "Sorted array: ${arr[@]}"

Key Concept

Array handling with -a flag. ${#arr[@]} gets array length. Bubble sort swaps elements. This teaches fundamental sorting algorithms.

Q11. Create a datafile which contain given format and perform the given operation on that data file using grep.

Problem Explanation

This script uses grep to search, filter, and extract data from structured files using pattern matching.

Key Concept

grep searches for patterns. -i ignores case. -v inverts match. -c counts matches. This is essential for log analysis and data extraction.

Q12. Write a awk program to display stock report with given format.

Problem Explanation

AWK is a powerful text processing language. This script generates formatted stock reports with calculations from data files.

Code Example

AWK
awk 'BEGIN {print "Stock Report"} 
{print $1, $2, $3, $2*$3} 
END {print "End of Report"}' stockfile.txt

Key Concept

AWK processes files line by line. BEGIN/END blocks execute before/after. $1,$2,$3 access fields. This is ideal for report generation.

Q13. Write a awk program to display customer earning report with given format.

Problem Explanation

Similar to Q12, this script uses AWK to calculate and display customer earnings with proper formatting and calculations.

Code Example

AWK
awk 'BEGIN {printf "%-15s %-10s %-10s\n", "Customer", "Sales", "Commission"}
{commission=$2*0.1; printf "%-15s %-10d %-10.2f\n", $1, $2, commission}' customers.txt

Key Concept

printf enables formatted output. %-15s left-aligns strings. %.2f formats decimal places. AWK excels at columnar data formatting.