Learn, Practice, and Master Shell Scripting | House of Script
Script Editor
1
Pre-built Examples
Output
Bash Syntax Quick Reference
Numeric Comparison Operators
-eq
Equal to (e.g., [ $a -eq $b ])
-ne
Not equal to
-lt
Less than
-gt
Greater than
-le
Less than or equal to
-ge
Greater than or equal to
String Comparison Operators
=
String equality (e.g., [ "$a" = "$b" ])
!=
String inequality
-z
String is empty (zero length)
-n
String is not empty (non-zero length)
File Test Operators
-f
File exists and is a regular file
-d
Directory exists
-e
File or directory exists
-r
File is readable
-w
File is writable
-x
File is executable
-s
File exists and is not empty
Logical Operators
&&
Logical AND (command1 && command2)
||
Logical OR (command1 || command2)
!
Logical NOT (! command)
-a
AND within test [ cond1 -a cond2 ]
-o
OR within test [ cond1 -o cond2 ]
Arithmetic Operations
$((expr))
Arithmetic expansion: result=$((5 + 3))
let
Arithmetic evaluation: let "a = 5 + 3"
expr
External calculator: result=$(expr 5 + 3)
+, -, *, /, %
Basic arithmetic operators
Common Bash Constructs
$variable
Variable expansion
$(command)
Command substitution
${var}
Variable expansion with braces
"$var"
Quoted variable (preserves spaces)
Progressive Challenges
Challenge 1: Number Printer
Easy
Write a bash script that prints numbers from 1 to 10, each on a new line.
Requirements:
Use a for loop or while loop
Print each number on a separate line
Output should be: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Hints
- Use a for loop: for i in {1..10}
- Or a while loop with a counter variable
- Use echo to print each number
Challenge 2: File Existence Checker
Medium
Write a script that checks if a file exists and displays appropriate messages.
Requirements:
Define a variable with a filename (e.g., "config.txt")
Use an if statement with the -f test operator
Print "File exists!" if it exists
Print "File does not exist!" if it doesn't
Hints
- Use: if [ -f "$filename" ]
- Remember to use quotes around variables
- The -f operator tests for regular files
- For simulation, assume the file doesn't exist
Challenge 3: Factorial Calculator
Hard
Write a script that calculates the factorial of a given number using a function.
Requirements:
Create a function called "factorial" that takes one parameter
Use a loop to calculate the factorial
Return/echo the result
Test with factorial of 5 (should be 120)
Hints
- Define function: factorial() { ... }
- Access parameter with $1
- Initialize result=1
- Use a while loop: while [ $i -le $n ]
- Calculate: result=$((result * i))
- Echo the result at the end