You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Shell scripting allows you to automate tasks by writing sequences of commands in a file. Bash (Bourne Again Shell) is the default shell on most Linux distributions and the most widely used scripting shell.
#!/bin/bash
# my_first_script.sh — a simple example
echo "Hello, World!"
echo "Today is $(date +%Y-%m-%d)"
echo "You are logged in as: $USER"
chmod +x my_first_script.sh # make it executable
./my_first_script.sh # run it
bash my_first_script.sh # or run explicitly with bash
The first line #!/bin/bash (called the shebang) tells the system which interpreter to use:
| Shebang | Interpreter |
|---|---|
#!/bin/bash | Bash shell |
#!/bin/sh | POSIX-compatible shell |
#!/usr/bin/env python3 | Python 3 |
#!/usr/bin/env node | Node.js |
# Assigning variables (no spaces around =)
name="Alice"
age=30
current_dir=$(pwd)
file_count=$(ls | wc -l)
# Using variables
echo "Name: $name"
echo "Age: $age"
echo "Directory: $current_dir"
echo "Files: $file_count"
# Curly braces for clarity
echo "Hello, ${name}!"
echo "File: ${name}_report.txt"
# Read-only variables
readonly PI=3.14159
# Unsetting variables
unset age
| Variable | Meaning |
|---|---|
$0 | Script name |
$1, $2, ... | Positional arguments |
$# | Number of arguments |
$@ | All arguments (as separate words) |
$* | All arguments (as a single string) |
$? | Exit code of the last command |
$$ | PID of the current script |
$! | PID of the last background process |
#!/bin/bash
if [ -f "/etc/nginx/nginx.conf" ]; then
echo "Nginx is configured"
elif [ -f "/etc/apache2/apache2.conf" ]; then
echo "Apache is configured"
else
echo "No web server found"
fi
File tests:
| Operator | Test |
|---|---|
-f file | File exists and is a regular file |
-d dir | Directory exists |
-e path | Path exists (file or directory) |
-r file | File is readable |
-w file | File is writable |
-x file | File is executable |
-s file | File exists and is not empty |
-L file | File is a symbolic link |
String tests:
| Operator | Test |
|---|---|
-z "$var" | String is empty |
-n "$var" | String is not empty |
"$a" = "$b" | Strings are equal |
"$a" != "$b" | Strings are not equal |
Numeric tests:
| Operator | Test |
|---|---|
$a -eq $b | Equal |
$a -ne $b | Not equal |
$a -gt $b | Greater than |
$a -lt $b | Less than |
$a -ge $b | Greater than or equal |
$a -le $b | Less than or equal |
[[ ]] Syntax# Supports && and || directly, pattern matching, and regex
if [[ "$name" == "Alice" && "$age" -gt 18 ]]; then
echo "Adult Alice"
fi
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.