Bash Scripting Basics

Learn the foundations of writing Bash shell scripts.

1. Shebang

#!/bin/bash

Indicates the script should run in Bash.

2. Variables

name="Alice"

Declares a variable.

3. Echo

echo "Hello $name"

Prints output to the terminal.

4. Read

read username

Takes user input and stores in variable.

5. If Statement

if [ $x -eq 1 ]; then echo "One"; fi

Conditional logic in Bash.

6. For Loop

for i in 1 2 3; do echo $i; done

Loops through a list of values.

7. While Loop

while [ $x -lt 5 ]; do echo $x; x=$((x+1)); done

Repeats as long as condition is true.

8. Functions

greet() { echo "Hi $1"; }

Defines a reusable block of code.

9. Case Statement

case $var in 1) echo One;; esac

Pattern matching like switch-case.

10. Exit Status

echo $?

Checks result of last command.

11. Comments

# This is a comment

Used to document code.

12. Command Substitution

today=$(date)

Captures command output into a variable.

13. Test Command

test -f file.txt

Checks file types or conditions.

14. Quotes

echo "