Modern QA2026Useful Bash Constructs — tiles
Log inJoin
75 / 80 · 12 Programming for QA · Bash Scripting for QA← prev⊞ allnext →☰ Read as one page

9.5Useful Bash Constructs

Conditional Execution

# Run smoke tests first, only run full suite if smoke passes
pytest tests/smoke/ && pytest tests/full/

# Run cleanup regardless of test outcome
pytest tests/ || true
./cleanup.sh

File and Directory Operations

# Create test output directory
mkdir -p test-results/screenshots

# Check if file exists
if [ -f "test-data.sql" ]; then
    psql testdb < test-data.sql
else
    echo "WARNING: test-data.sql not found"
fi

# Clean up old test artifacts
find test-results/ -name "*.png" -mtime +7 -delete

Looping and Parallel Execution

# Run tests for each environment
for env in staging production; do
    echo "Testing $env..."
    API_BASE_URL="https://${env}.example.com" pytest tests/smoke/ \
        --junitxml="results-${env}.xml"
done

# Parallel execution with xargs
echo "staging production sandbox" | tr ' ' '\n' | \
    xargs -P 3 -I {} bash -c 'API_BASE_URL="https://{}.example.com" pytest tests/smoke/'

String Processing

# Extract test count from pytest output
RESULT=$(pytest tests/ --tb=no 2>&1 | tail -1)
echo "Result: $RESULT"
# "5 passed, 2 failed in 12.3s"

# Check if tests failed
if echo "$RESULT" | grep -q "failed"; then
    echo "TESTS FAILED"
    exit 1
fi