Linux Shell Scripting Basics
Q1. Write a shell script using if statements to check file exists or not.
Problem Explanation
This shell script checks if a file exists at a given path. It uses the -f test operator within an if statement to verify file existence before performing operations.
Step-By-Step Instructions
- Create a shell script file (script.sh)
- Add shebang line #!/bin/bash
- Accept filename as command-line argument
- Use -f test operator to check file existence
- Display appropriate message
- Make script executable (chmod +x)
Code
#!/bin/bash
if [ -f "$1" ]; then
echo "File $1 exists"
else
echo "File $1 does not exist"
fi
Output
Key Concept
The [ -f file ] test checks if file exists and is a regular file. Quotes "$1" protect arguments with spaces. if-fi blocks provide conditional execution. This is essential for file management scripts.
Q2. Write shell script to copy a file.
Problem Explanation
This script copies a file from source to destination using the cp command. It includes error checking to ensure source file exists before copying.
Step-By-Step Instructions
- Accept source and destination arguments
- Check if source file exists
- Use cp command to copy file
- Display success or error message
Code
#!/bin/bash
if [ $# -ne 2 ]; then
echo "Usage: $0 source destination"
exit 1
fi
if [ ! -f "$1" ]; then
echo "Source file $1 does not exist"
exit 1
fi
cp "$1" "$2"
echo "File copied successfully from $1 to $2"
Output
Key Concept
$# returns number of arguments. -ne tests inequality. exit 1 signals error. This script validates inputs before executing commands, preventing accidental data loss.
Q3. Write a shell script to check the given number is odd or even.
Problem Explanation
This script uses the modulo operator (%) within shell arithmetic to determine if a number is even or odd. Even numbers have remainder 0 when divided by 2.
Step-By-Step Instructions
- Read number from user or command-line
- Use modulo operator (number % 2)
- If remainder is 0, number is even
- Otherwise, number is odd
Code
#!/bin/bash
read -p "Enter a number: " num
if [ $((num % 2)) -eq 0 ]; then
echo "$num is Even"
else
echo "$num is Odd"
fi
Output
Key Concept
$((expression)) performs arithmetic evaluation in bash. read command accepts user input with prompt. -eq tests numeric equality. This demonstrates basic arithmetic in shell scripts.
Q4. Write a shell script to check file permission.
Problem Explanation
This script checks file access permissions using test operators: -r (readable), -w (writable), -x (executable). It helps determine what operations can be performed on a file.
Key Operators
- -r file: File is readable
- -w file: File is writable
- -x file: File is executable
- -f file: Is a regular file
- -d file: Is a directory
Code Example
#!/bin/bash
file="./myfile.txt"
if [ -r "$file" ]; then echo "File is readable"; fi
if [ -w "$file" ]; then echo "File is writable"; fi
if [ -x "$file" ]; then echo "File is executable"; fi
Key Concept
File permissions control access security. Test operators check individual permissions. This is essential for access control and security verification in shell scripts.
Q5. Write a shell script to calculate the grade of Student.
Problem Explanation
This script calculates student grade based on marks using conditional statements. Typical grading: A (90+), B (80+), C (70+), D (60+), F (below 60).
Code Example
#!/bin/bash
read -p "Enter marks: " marks
if [ $marks -ge 90 ]; then echo "Grade: A"
elif [ $marks -ge 80 ]; then echo "Grade: B"
elif [ $marks -ge 70 ]; then echo "Grade: C"
elif [ $marks -ge 60 ]; then echo "Grade: D"
else echo "Grade: F"
fi
Key Concept
elif chains multiple conditions. -ge tests greater-than-or-equal. This demonstrates conditional logic for educational grading systems.
Q6. Write a shell script to find out given word is contains vowel and also check the entered vowel is small case or capital.
Problem Explanation
This script checks if a word contains vowels and determines their case (uppercase or lowercase). It uses pattern matching with grep or case statements.
Key Techniques
- Iterate through each character
- Check if character is a vowel
- Determine case using [[ ]] patterns
- Display results
Key Concept
Pattern matching identifies character types. String manipulation extracts individual characters. Case analysis helps in text processing and validation.
Q7. Write a shell script to display given year is leap year or not.
Problem Explanation
Leap year logic: Divisible by 400 OR (Divisible by 4 AND NOT divisible by 100). This script uses complex conditional logic.
Code Example
#!/bin/bash
read -p "Enter year: " year
if [ $((year % 400)) -eq 0 ] || { [ $((year % 4)) -eq 0 ] && [ $((year % 100)) -ne 0 ]; }; then
echo "$year is a Leap Year"
else
echo "$year is not a Leap Year"
fi
Key Concept
Complex boolean logic with || (OR) and && (AND). This teaches important date logic and algorithmic thinking in shell scripting.
Q8. Write a shell script to greet message according to time.
Problem Explanation
This script uses the date command to get current hour and displays appropriate greeting: "Good Morning" (6-12), "Good Afternoon" (12-18), or "Good Evening" (18-6).
Key Concept
date command retrieves system time. String manipulation extracts hour. Conditional logic selects appropriate greeting. This demonstrates time-based program behavior.
Q9. Write a shell script to print the Fibonacci series.
Problem Explanation
Fibonacci series: Each number is sum of previous two (0, 1, 1, 2, 3, 5, 8...). This script uses a while loop to generate the series up to N terms.
Code Example
#!/bin/bash
read -p "Enter number of terms: " n
a=0
b=1
echo "Fibonacci Series:"
for ((i=0; i
Key Concept
Loop iteration generates series. Variable swapping implements Fibonacci logic. for loops with arithmetic expansion provide control. This teaches algorithmic sequences.
Q10. Write a shell script to print the number between 0 to 9.
Problem Explanation
Simple script using a for loop to iterate from 0 to 9 and display each number. Demonstrates basic looping constructs in shell scripting.
Code Example
#!/bin/bash
echo "Numbers from 0 to 9:"
for i in {0..9}
do
echo $i
done
Key Concept
Bash brace expansion {0..9} generates sequence. for-in loops iterate values. echo displays output. This introduces fundamental loop structures.
Q11. Write a shell script to read name, gender and marital status display the same.
Problem Explanation
This script reads multiple inputs from user (name, gender, marital status) and displays them together. Demonstrates input collection and formatted output.
Code Example
#!/bin/bash
read -p "Enter name: " name
read -p "Enter gender: " gender
read -p "Enter marital status: " status
echo "Name: $name"
echo "Gender: $gender"
echo "Marital Status: $status"
Key Concept
read command captures user input with prompts. Variables store values. echo displays formatted output. This demonstrates basic input/output operations.