100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Bash Scripting Cheat Sheet

Bash Scripting Cheat Sheet

Practical Bash scripting reference covering variables, conditionals, loops, string/array handling, and common builtins.

2 PagesBeginnerApr 10, 2026

Basics

Variables and script arguments.

bash
#!/bin/bash# Variables (no spaces around =)name="World"echo "Hello, $name!"readonly PI=3.14159          # constantecho "Args: $1 $2, count: $#"echo "Script name: $0"

Conditionals

if/elif/else and test expressions.

bash
x=10if [ "$x" -gt 5 ]; then    echo "big"elif [ "$x" -eq 5 ]; then    echo "equal"else    echo "small"fi# String comparison[ "$name" == "World" ] && echo "matched"# Test file existence[ -f "/etc/passwd" ] && echo "file exists"

Loops

for and while loops.

bash
for i in 1 2 3 4 5; do    echo "i=$i"donefor f in *.txt; do    echo "Found $f"donecount=0while [ $count -lt 3 ]; do    echo "count=$count"    count=$((count + 1))done

Strings & Arrays

Manipulating strings and arrays.

  • ${#str}- Length of a string
  • ${str:0:3}- Substring starting at index 0, length 3
  • arr=(a b c)- Declares an indexed array
  • ${arr[@]}- Expands to all array elements
  • ${arr[1]}- Accesses the element at index 1
  • ${str/foo/bar}- Replaces the first occurrence of foo with bar

Common Builtins

Useful builtins and idioms.

  • $(cmd)- Command substitution, captures command output
  • set -euo pipefail- Exit on error, unset variable, or pipeline failure
  • trap 'cleanup' EXIT- Runs the cleanup function when the script exits
  • read -p "Prompt: " var- Prompts for and reads user input into var
  • function name() { ...; }- Defines a reusable shell function
  • $?- Exit status of the last executed command
Pro Tip

Always quote variable expansions ("$var") to prevent word splitting and glob expansion on values containing spaces or special characters.

Was this cheat sheet helpful?

Explore Topics

#BashScripting#BashScriptingCheatSheet#Programming#Beginner#Conditionals#Loops#StringsArrays#CommonBuiltins#DataStructures#CommandLine#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet