Shell scripting if else
Shell scripting if else
Below is a
detailed explanation of each section:
Explanation:
Explanation:
3️⃣ Using ((
... )) (Double Parentheses)
bash
CopyEdit
a=$(( 4 + 5 ))
echo $a # Output: 9
a=$((3+5))
echo $a # Output: 8
b=$(( a + 3 ))
echo $b # Output: 11
b=$(( $a + 4 ))
echo $b # Output: 12
(( b += 3 )) # Adds 3 to `b`
echo $b # Output: 16
a=$(( 4 * 5 ))
echo $a # Output: 20
Explanation:
c=$((a+b))
echo "Addition: $c"
Explanation:
bash
CopyEdit
echo "First number: "
read a
Explanation:
c=$((a * b))
echo "Multiplication: $c"
Explanation:
bash
CopyEdit
c=$((a / b))
echo "Division: $c"
Explanation:
Key Takeaways:
Corrected Script
bash
CopyEdit
#!/bin/bash
c=$((a + b))
echo "Addition: $c"
How It Works:
1. echo "First number: " → Prints a prompt for the first number.
2. read a → Reads user input and stores it in a.
3. echo "Second number: " → Prints a prompt for the second number.
4. read b → Reads user input and stores it in b.
5. c=$((a + b)) → Performs addition and stores the result in c.
6. echo "Addition: $c" → Displays the result.
Example Run
bash
CopyEdit
$ ./script.sh
First number:
5
Second number:
7
Addition: 12
Would you like to extend this script with subtraction, multiplication, or division?
4o
You said:
If else condition in shell sription and give me all the coding examples very simple and easy to do
ChatGPT said:
ChatGPT
The if-else statement allows conditional execution of commands. Here are some simple
examples.
num=10
Explanation:
Explanation:
if [ -f "$filename" ]; then
echo "The file exists"
else
echo "The file does not exist"
fi
Explanation:
Explanation:
Explanation:
Explanation:
Operator Meaning
-eq Equal to
-ne Not equal to
-gt Greater than
-lt Less than
-ge Greater than or equal to
-le Less than or equal to
= String equal
!= String not equa