Shell Scripting Basics
Objective
Write your first shell scripts with variables, user input, and proper structure including shebang line, exit codes, and basic I/O.
Tools & Technologies
bashvariablesreadechoexit codesshebang
Key Commands
#!/bin/bashchmod +x script.sh./script.sh$? for exit coderead -p 'Input: ' varArchitecture Overview
flowchart TD
EDIT[Write script.sh] --> SHEBANG[Add shebang\n#!/bin/bash]
SHEBANG --> PERM[chmod +x script.sh]
PERM --> RUN[./script.sh]
RUN --> EXEC[Shell executes\nline by line]
EXEC --> EXIT[Exit code $?\n0=success 1+=error]
style SHEBANG fill:#1a1a2e,stroke:#00d4ff,color:#e0e0e0
style RUN fill:#1a1a2e,stroke:#00ff88,color:#e0e0e0
Step-by-Step Process
01
Script Structure
Every script starts with a shebang line. Set executable permission before running.
#!/bin/bash
# This is a comment
# Script: hello.sh
echo 'Hello, World!'
NAME='Taki'
echo "Hello, $NAME"
echo 'No expansion: $NAME' # single quotes = literal
02
Variables
Variables store values. No spaces around =. Use $VAR or ${VAR} to expand.
AGE=25
GREETING='Hello'
FILE=/etc/hosts
echo $AGE
echo ${GREETING}, user!
echo "File: $FILE"
# Command substitution
DATE=$(date +%Y-%m-%d)
FILES=$(ls | wc -l)
echo "Today: $DATE, Files: $FILES"
03
User Input
Use read to get input from the user during script execution.
#!/bin/bash
read -p 'Enter your name: ' NAME
read -sp 'Enter password: ' PASS # silent
echo
echo "Welcome, $NAME!"
# Read with timeout
read -t 5 -p 'Continue? [y/n]: ' CHOICE
04
Exit Codes
Commands return exit codes: 0 = success, non-zero = failure. Check $? after each command.
#!/bin/bash
ping -c1 8.8.8.8 > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo 'Network OK'
else
echo 'Network FAIL'
exit 1
fi
# Better pattern:
if ping -c1 8.8.8.8 > /dev/null 2>&1; then
echo 'OK'
fi
Challenges & Solutions
- Forgetting chmod +x makes script 'Permission denied'
- Variable assignment with spaces causes 'command not found' error
Key Takeaways
- Use #!/usr/bin/env bash for portability across systems
- Always quote variable expansions: "$VAR" prevents word splitting bugs