shell script collection

 1.Write a Simple shell script for basic arithmetic and logical calculations.

✅ Shell Script: calc.sh

#!/bin/bash

# Basic Arithmetic and Logical Calculations

echo "Enter first number:"

read a

echo "Enter second number:"

read b

# Arithmetic Operations

sum=$((a + b))

diff=$((a - b))

prod=$((a * b))

div=$((a / b))

mod=$((a % b))

echo "Arithmetic Calculations:"

echo "$a + $b = $sum"

echo "$a - $b = $diff"

echo "$a * $b = $prod"

echo "$a / $b = $div"

echo "$a % $b = $mod"

# Logical Comparisons

echo "Logical Comparisons:"

if [ $a -eq $b ]; then

echo "$a is equal to $b"

else

echo "$a is not equal to $b"

fi

if [ $a -gt $b ]; then

echo "$a is greater than $b"

else

echo "$a is not greater than $b"

fi

if [ $a -lt $b ]; then

echo "$a is less than $b"

else

echo "$a is not less than $b"

fi

๐Ÿ’ป How to Run It

1. Save the script to a file named calc.sh.

Make it executable:

chmod +x calc.sh

2. Run it:

./calc.sh

2.Write a shell script to display a list of users currently logged in.

Here's a simple shell script that displays a list of users currently logged into the

system:

#!/bin/bash

# Script to display a list of users currently logged in

echo "Currently logged in users:"

who | awk '{print $1}' | sort | uniq

Explanation:

● who: Shows who is logged on.

● awk '{print $1}': Extracts the username from each line.

● sort: Sorts the usernames alphabetically.

● uniq: Removes duplicate entries.

To use the script:

1. Save the script to a file, for example: logged_in_users.sh

Make it executable:

chmod +x logged_in_users.sh

2. Run it:

./logged_in_users.sh

3. Let me know if you want to include login times or terminals as well.

3.Write a shell script to delete all the temporary files.

#!/bin/bash

# Script to delete all temporary files

# Define directories to search for temporary files

TEMP_DIRS=("/tmp" "$HOME/tmp" "$HOME")

echo "Deleting temporary files..."

# Delete common temp files from these directories

for dir in "${TEMP_DIRS[@]}"; do

if [ -d "$dir" ]; then

echo "Checking $dir ..."

# Delete files ending in ~ or .tmp

find "$dir" -type f \( -name "*.tmp" -o -name "*~" \) -exec rm -f {} \;

fi

done

echo "Temporary files deleted."

Explanation:

● TEMP_DIRS: A list of directories to search for temp files.

● find: Searches for files matching patterns (*.tmp, *~) and deletes them.

● rm -f: Forcefully removes the matched files without prompting.

To use the script:

1. Save it as delete_temp_files.sh

Make it executable:

chmod +x delete_temp_files.sh

2. Run it:

./delete_temp_files.sh

2.⚠️ Warning: This script deletes files. Always double-check the

directories and file patterns to ensure important data is not accidentally

removed.

Would you like it to cover more system-wide temp locations (like /var/tmp) or

add logging?

4.Write a shell script to search an element from an array using binary

searching. ✅ Shell Script: Binary Search in an Array

#!/bin/bash

# Binary Search Function

binary_search() {

local arr=("$@")

local key=${arr[-1]} # Last argument is the key

unset arr[-1] # Remove key from array

local low=0

local high=$((${#arr[@]} - 1))

while [ $low -le $high ]; do

local mid=$(( (low + high) / 2 ))

if [ "${arr[$mid]}" -eq "$key" ]; then

echo "Element $key found at index $mid."

return 0

elif [ "${arr[$mid]}" -lt "$key" ]; then

low=$((mid + 1))

else

high=$((mid - 1))

fi

done

echo "Element $key not found in the array."

return 1

}

# Main Script

echo "Enter sorted array elements separated by space:"

read -a array

echo "Enter the element to search:"

read key

# Call binary search

binary_search "${array[@]}" "$key"

๐Ÿงช Example Usage

$ bash binary_search.sh

Enter sorted array elements separated by space:

1 3 5 7 9 11

Enter the element to search:


7

Element 7 found at index 3.

5.Write a shell script to determine whether a given number is a prime

number or not

✅ Shell Script: Check Prime Number

#!/bin/bash

echo -n "Enter a number: "

read num

# Handle edge cases

if [ "$num" -le 1 ]; then

echo "$num is not a prime number."

exit 0

fi

# Check for prime

is_prime=1

for (( i=2; i*i<=num; i++ ))

do

if (( num % i == 0 )); then

is_prime=0

break

fi

done

if [ $is_prime -eq 1 ]; then

echo "$num is a prime number."

else

echo "$num is not a prime number."

fi


๐Ÿงช Example Run

$ bash check_prime.sh

Enter a number: 17

17 is a prime number.

$ bash check_prime.sh

Enter a number: 12

12 is not a prime number.


๐Ÿ” How it works:

● It checks divisibility from 2 to √num (i.e., i*i <= num), which is efficient.

● If a divisor is found, it's not a prime.

Let me know if you want a version using functions or to check multiple numbers

in one run!

8.Write a shell script to print the first n Fibonacci numbers.

#!/bin/bash

# Prompt user for the number of terms

read -p "Enter the number of Fibonacci numbers to print: " n

# Check if n is a valid positive integer

if ! [[ "$n" =~ ^[0-9]+$ ]] || [ "$n" -le 0 ]; then

echo "Please enter a valid positive integer."

exit 1

fi

# Initialize first two Fibonacci numbers

a=0

b=1

echo "The first $n Fibonacci numbers are:"

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

do

echo -n "$a "

fn=$((a + b))

a=$b

b=$fn

done

echo

How to Use:

1. Save this script as fibonacci.sh.

Make it executable:

chmod +x fibonacci.sh

2. Run it:

./fibonacci.sh

Example Output:

Enter the number of Fibonacci numbers to print: 7

The first 7 Fibonacci numbers are:


0 1 1 2 3 5 8

9.Execute various system administrative commands

If you're asking how to execute various system administrative commands

using a shell script, here's a script that demonstrates several common

Linux/Unix system admin tasks. ✅ Shell Script to Execute System Administrative Commands

#!/bin/bash

echo "System Administrative Tasks Script"

# 1. Display current date and time

echo -e "\n1. Current date and time:"

date

# 2. Display system uptime

echo -e "\n2. System uptime:"

uptime

# 3. Display currently logged-in users

echo -e "\n3. Currently logged-in users:"

who

# 4. Show disk usage

echo -e "\n4. Disk usage:"

df -h

# 5. Show memory usage

echo -e "\n5. Memory usage:"

free -h

# 6. Show currently running processes (top 5)

echo -e "\n6. Top 5 running processes by CPU usage:"

ps aux --sort=-%cpu | head -n 6

# 7. Show IP address

echo -e "\n7. IP address of the system:"

ip a | grep inet

# 8. Show open ports (requires sudo)

echo -e "\n8. Open network ports (using ss):"

sudo ss -tuln

# 9. Show system load averages

echo -e "\n9. Load averages:"

cat /proc/loadavg

# 10. List all services (for systems with systemd)

echo -e "\n10. List running services (systemd-based systems):"

systemctl list-units --type=service --state=running

echo -e "\nSystem admin tasks completed."


๐Ÿ”ง To Run:

1. Save as admin_tasks.sh

Make it executable:

chmod +x admin_tasks.sh

2. Run it:

./admin_tasks.sh

3. Use sudo ./admin_tasks.sh if you want commands like ss or

systemctl to work without permission errors.

Comments

Popular posts from this blog

Shell Scripting Codes - Loops

OS Lab Record