Topic Shell Programming & Scripting
Topic Shell Programming & Scripting
&
Shell Scripting
#!/bin/bash
Display output
Conditional statements
fi
For loop
for i in {1..5}; do
done
While loop
count=5
count=$((count - 1))
done
Mathematical operations
num1=10
num2=5
sum=$((num1 + num2))
Command substitution
current_date=$(date)
Function declaration
greet() {
greet "Satyam"
if [ -f "output.txt" ]; then
fi
./another_script.sh
Permission change
chmod +x script.sh
Coding Part
Conditional Statement: Even or Odd Check
bash
CopyEdit
#!/bin/bash
else
Fi
How it Works:
bash
CopyEdit
#!/bin/bash
done
How it Works:
• The for loop iterates from 1 to 5 using arithmetic expression syntax (( )).
Conditional + Looping: Print Multiplication Table
bash
CopyEdit
#!/bin/bash
result=$((num * i))
done
bash
CopyEdit
#!/bin/bash
count=5
count=$((count - 1))
done
bash
CopyEdit
#!/bin/bash
while true; do
case $choice in
1) date ;;
2) ls ;;
3) whoami ;;
esac
done
How it Works:
• The while loop keeps displaying the menu until the user selects 4.
4o
You said:
maths realted question
ChatGPT said:
ChatGPT
Here are a few basic shell scripts to perform mathematical operations and solve simple math-related
tasks:
bash
CopyEdit
#!/bin/bash
case $choice in
1) result=$((num1 + num2))
2) result=$((num1 - num2))
3) result=$((num1 * num2))
else
result=$((num1 / num2))
fi ;;
esac
2. Factorial of a Number
bash
CopyEdit
#!/bin/bash
factorial=1
factorial=$((factorial * i))
done
bash
CopyEdit
#!/bin/bash
is_prime=0
else
is_prime=0
break
fi
done
fi
else
fi
4. Sum of Digits
bash
CopyEdit
#!/bin/bash
sum=0
digit=$((num % 10))
sum=$((sum + digit))
num=$((num / 10))
done
5. Fibonacci Sequence
bash
CopyEdit
#!/bin/bash
a=0
b=1
fn=$((a + b))
a=$b
b=$fn
done
echo