api: YAML JSON TOON Database version: 1.0.0 format: toon dataset: id: 2893 slug: shell-scripting-guide title: Shell Scripting Guide (Bash) description: "Comprehensive reference for Bash shell scripting: variables, control flow, functions, error handling, debugging, and best practices." summary: "A guide to Bash scripting by topic with examples: variables and expansion, control flow, functions, error handling, file operations, arrays and maps, debugging and best practices." use_when[2]: You are writing or reviewing a shell script.,You need a safe idiom for a common scripting task. caveats[2]: "Bash-specific features (arrays, [[ ]]) are not available in POSIX sh; set the shebang accordingly.","Use set -euo pipefail and quote variables, and consider a different language for complex logic." related[4]: file-operations,git-essential-commands,unix-text-processing-commands,cicd-pipeline-stages entry_count: 8 fields[2]{section,field,type,example}: sections,topic,string,Variables and Expansion sections,examples,array,"[4 items]" category: Unix Commands category_slug: unix-commands tags: "bash,shell,scripting,unix,linux,automation,devops" view_count: 44 created_at: 1777673262 updated_at: 1777673262 data: sections[8]: - topic: Variables and Expansion examples[4]{name,code}: Simple assignment,"name=\"John\"\necho \"Hello, $name\"" Command substitution,"current_dir=$(pwd)\necho \"We are in $current_dir\"" Default values,"echo \"${PORT:-8080}\" # prints 8080 if PORT unset\necho \"${PORT:=8080}\" # sets PORT to 8080 if unset\necho \"${PORT:?Error: PORT required}\" # exits if unset" String manipulation,"str=\"hello_world.txt\"\necho \"${str%.*}\" # hello_world (remove shortest suffix)\necho \"${str##*.}\" # txt (remove longest prefix)\necho \"${str/_/-}\" # hello-world.txt (replace first _)" - topic: Control Flow examples[4]{name,code}: If statement,"if [ -f \"$file\" ]; then\n echo \"File exists\"\nelif [ -d \"$file\" ]; then\n echo \"Is a directory\"\nelse\n echo \"Not found\"\nfi" For loop,"for item in \"${array[@]}\"; do\n echo \"Processing: $item\"\ndone\n\n# Or with range\nfor i in {1..10}; do\n echo \"Count: $i\"\ndone" While loop,"while IFS= read -r line; do\n echo \"Line: $line\"\ndone < \"input.txt\"" Case statement,"case \"$1\" in\n start) echo \"Starting...\";;\n stop) echo \"Stopping...\";;\n restart) echo \"Restarting...\";;\n *) echo \"Usage: $0 {start|stop|restart}\"; exit 1;;\nesac" - topic: Functions examples[3]{name,code}: Define and call,"greet() {\n local name=\"$1\"\n echo \"Hello, $name!\"\n}\n\ngreet \"World\" # Hello, World!" Return values,"is_even() {\n local num=$1\n return $(( num % 2 ))\n}\n\nif is_even 42; then\n echo \"Even\"\nelse\n echo \"Odd\"\nfi" Output capture,"get_date() {\n date \"+%Y-%m-%d\"\n}\n\ntoday=$(get_date)\necho \"Today is $today\"" - topic: Error Handling examples[3]{name,code}: Exit on error,"set -e # Exit immediately on error\nset -u # Error on undefined variables\nset -o pipefail # Fail pipeline on first error\n\n# Combined\nset -euo pipefail" Trap signals,"cleanup() {\n echo \"Cleaning up...\"\n rm -f /tmp/tempfile\n exit\n}\n\ntrap cleanup EXIT SIGINT SIGTERM" Check command success,"if ! command -v docker &> /dev/null; then\n echo \"Docker is not installed\"\n exit 1\nfi" - topic: File Operations examples[3]{name,code}: Read file line by line,"while IFS= read -r line; do\n echo \"$line\"\ndone < \"input.txt\"" Check file conditions,"if [ -f \"$file\" ]; then echo \"regular file\"; fi\nif [ -d \"$dir\" ]; then echo \"directory\"; fi\nif [ -x \"$bin\" ]; then echo \"executable\"; fi\nif [ -z \"$str\" ]; then echo \"empty string\"; fi\nif [ -n \"$str\" ]; then echo \"non-empty\"; fi" Temp files,"tempfile=$(mktemp)\necho \"Writing to $tempfile\"\n# ... use it ...\nrm -f \"$tempfile\"" - topic: Arrays and Maps examples[2]{name,code}: Indexed array,"fruits=(\"apple\" \"banana\" \"cherry\")\necho \"${fruits[0]}\" # apple\necho \"${#fruits[@]}\" # length 3\necho \"${fruits[@]}\" # all elements" Associative array (Bash 4+),"declare -A config\nconfig[\"host\"]=\"localhost\"\nconfig[\"port\"]=8080\n\necho \"${config[host]}\" # localhost" - topic: Debugging examples[3]{name,code}: Enable debug mode,"set -x # Print commands and their arguments as executed\n# ... debug code ...\nset +x # Disable debug\n\n# Or run script with:\n# bash -x script.sh" Check syntax without running,"bash -n script.sh\n# Returns silently if syntax is valid" ShellCheck static analysis,"# Install: apt install shellcheck / brew install shellcheck\n# Run: shellcheck script.sh\n# Catches: unquoted variables, missing shebang, common pitfalls" - topic: Best Practices examples[3]{name,code}: Script header,"#!/usr/bin/env bash\nset -euo pipefail\nIFS=$'\\n\\t'" Usage function,"usage() {\n cat <