Basic Script Structure
Bash
#!/bin/bash
set -euo pipefail
main() {
echo " when"
}
main "$@"Variables
Bash
NAME="SecuThive"
echo ", $NAME"
echo ': $NAME' # Single quotes preserve the literal string
readonly VERSION="1.0.0"
PORT="${PORT:-8080}" # Default value
SERVERS=("web1" "web2" "web3")
echo "${SERVERS[0]}" # web1
echo "${#SERVERS[@]}" # Number of elementsConditionals
Bash
FILE="/etc/nginx/nginx.conf"
if [[ -f "$FILE" ]]; then
echo "file "
elif [[ -d "$FILE" ]]; then
echo ""
else
echo ""
fi
if [[ "$ENV" == "production" ]]; then
echo " "
fi
if [[ $COUNT -gt 10 ]]; then
echo "10 "
fiFile Test Operators
| Expression | Meaning |
|---|---|
-f FILE | Regular file exists |
-d DIR | Directory exists |
-e PATH | Path exists |
-r FILE | File is readable |
-z STRING | String is empty |
-n STRING | String is not empty |
Loops
Bash
for server in "${SERVERS[@]}"; do
echo ": $server"
ssh "$server" "sudo systemctl restart myapp"
done
for i in {1..5}; do
echo "when $i"
done
COUNT=0
while [[ $COUNT -lt 3 ]]; do
echo " ..."
sleep 1
((COUNT++))
doneFunctions
Bash
log() {
local level="$1"
local msg="$2"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $msg"
}
check_service() {
local service="$1"
if systemctl is-active --quiet "$service"; then
log "INFO" "$service run "
return 0
else
log "ERROR" "$service "
return 1
fi
}
check_service nginx || exit 1Error Handling
Bash
if ! rsync -av /src/ user@host:/dest/; then
log "ERROR" "rsync failed"
exit 1
fi
TMPFILE=$(mktemp)
trap 'rm -f "$TMPFILE"; echo " "' EXIT
trap 'echo " : $LINENO"' ERREditorial note
AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us
Topic-related official docs (auto-linked · not per-claim sources)Linux man pages ↗
Questions & answers
Ask a question about this guide. We'll review and reply.