Sample Shell Programs

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

#!

/bin/bash

1. Hello world
# Hello World!
echo "Hello World!"

2. User Ip & op
echo "Enter your name:"
read username
echo "Hello, $username!"

3. Conditional (if-else)
echo "Enter a number:"
read number

if [ $number -gt 0 ]; then


echo "The number is positive."
elif [ $number -eq 0 ]; then
echo "The number is zero."
else
echo "The number is negative."
fi
4. Loop (for)
echo "Loop through numbers 1 to 5:"
for i in {1..5}; do
echo $i
done

5. Function
say_hello() {
echo "Hello from a function!"
}

say_hello

6. Command substitution
current_date=$(date)
echo "Current date: $current_date"

7. Arithmetic operations
num1=5
num2=3
sum=$((num1 + num2))
echo "Sum: $sum"
8. Arrays
fruits=("Apple" "Banana" "Orange")
echo "First fruit: ${fruits[0]}"

9. File existence checks


echo "Enter a filename:"
read filename

if [ -e "$filename" ]; then
echo "$filename exists."
else
echo "$filename does not exist."
fi

10. Function to find the biggest of three numbers


#!/bin/bash
# Function to find the biggest of three numbers
find_biggest() {
if [ $1 -gt $2 ] && [ $1 -gt $3 ]; then
echo "$1 is the biggest."
elif [ $2 -gt $3 ]; then
echo "$2 is the biggest."
else
echo "$3 is the biggest."
fi
}

# User input for three numbers


echo "Enter three numbers:"
read num1 num2 num3

# Call the function to find the biggest


find_biggest $num1 $num2 $num3

11. Function to calculate factorial


calculate_factorial() {
num=$1
factorial=1

while [ $num -gt 0 ]; do


factorial=$((factorial * num))
num=$((num - 1))
done

echo "Factorial of $1 is: $factorial"


}
# User input for factorial calculation
echo "Enter a number to calculate factorial:"
read input_num

# Call the function to calculate factorial


calculate_factorial $input_num

You might also like