32 / 55 · 19 Linux & Command Line · Bash Scripting for QA← prev⊞ allnext →☰ Read as one page
5.2Bash Fundamentals
Script Structure
#!/bin/bash
# The shebang line (first line) tells the system to use bash
# Exit immediately if a command fails
set -e
# Treat unset variables as an error
set -u
# Fail on pipe errors (not just the last command in a pipe)
set -o pipefail
# Your script logic goes here
echo "Script started at $(date)"
Make scripts executable: chmod +x my-script.sh
Run scripts: ./my-script.sh or bash my-script.sh
Variables
# Assignment (no spaces around =)
NAME="QA Engineer"
PORT=3000
BASE_URL="https://staging.example.com"
# Using variables
echo "Hello, $NAME"
echo "Server is at ${BASE_URL}:${PORT}"
# Default values (use default if variable is not set)
TIMEOUT=${TEST_TIMEOUT:-30000}
BROWSER=${TEST_BROWSER:-chromium}
# Command substitution (capture command output in a variable)
CURRENT_DATE=$(date +%Y-%m-%d)
GIT_HASH=$(git rev-parse --short HEAD)
Arrays
# Declare an array
ENVIRONMENTS=("dev" "staging" "preprod")
BROWSERS=("chromium" "firefox" "webkit")
# Access elements
echo "${ENVIRONMENTS[0]}" # First element: "dev"
echo "${ENVIRONMENTS[@]}" # All elements
echo "${#ENVIRONMENTS[@]}" # Count: 3
# Loop through an array
for env in "${ENVIRONMENTS[@]}"; do
echo "Testing $env..."
done