🚀 A comprehensive and deeply detailed Bash scripting cheatsheet covering all essential topics, categories, and examples.
| Category | Command/Concept | Description | Syntax/Example |
|---|---|---|---|
| Basic Syntax | #!/bin/bash |
Shebang to specify the interpreter to use for the script | #!/bin/bash |
| Comments | Add comments to code | # This is a comment |
|
| Variables | Declare variables (no spaces around =) |
name="John" |
|
| Printing | Print text to the console | echo "Hello, World!" |
|
| Data Types | Strings | Variables to store text | text="Hello" |
| Integers | Variables to store numbers | num=42 |
|
| Arrays | Variables to store multiple values | arr=(apple banana cherry) |
|
| Associative Arrays | Arrays with key-value pairs | declare -A arr; arr[fruit]="apple" |
|
| Operations | Arithmetic Operations | Perform basic math operations | echo $((3 + 5)) |
| String Operations | Concatenate or find string length | str="Hello"; echo "$str World" |
|
| Array Operations | Access, add, or remove elements in arrays | arr[1]="banana"; unset arr[0] |
|
| Control Structures | If Statements | Conditional execution based on criteria | if [ "$a" -gt "$b" ]; then echo "a is greater"; fi |
| Case Statements | Multi-way branching, similar to switch in other languages |
case $var in 1) echo "One";; 2) echo "Two";; esac |
|
| Loops | Repeat code execution | for i in {1..5}; do echo $i; done |
|
| While Loops | Execute while a condition is true | while [ "$a" -lt 5 ]; do echo $a; ((a++)); done |
|
| File Operations | Reading Files | Read content of a file | cat filename.txt |
| Writing to Files | Write output to a file | echo "Hello" > file.txt |
|
| Appending to Files | Append content to a file | echo "Append" >> file.txt |
|
| Check if File Exists | Check if a file or directory exists | if [ -f "file.txt" ]; then echo "Exists"; fi |
|
| File Permissions | Change file permissions | chmod 755 file.txt |
|
| Input and Output | Input from User | Get user input | read -p "Enter name: " name |
| Output Redirection | Redirect output to a file | ls > output.txt |
|
| Append Output | Append output to a file | echo "Line" >> output.txt |
|
| Error Redirection | Redirect errors | command 2> error.txt |
|
| Functions | Define Function | Define reusable function | function greet() { echo "Hello"; } |
| Call Function | Execute a function | greet |
|
| Parameters in Functions | Pass arguments to a function | function greet() { echo "Hello $1"; }; greet "John" |
|
| Return Values | Return a value from a function | function add() { return $(( $1 + $2 )); }; add 3 4; echo $? |
|
| Special Variables | $? |
Last command’s exit status | echo $? |
$# |
Number of arguments passed | echo $# |
|
$@ |
All arguments as separate words | echo $@ |
|
$* |
All arguments as a single string | echo $* |
|
$0 |
Script name | echo $0 |
|
$1, $2, ... |
Positional parameters | echo $1 |
|
| String Operations | String Length | Get length of a string | echo ${#string} |
| Substring Extraction | Extract part of a string | echo ${string:2:5} |
|
| String Replacement | Replace text within a string | echo ${string/foo/bar} |
|
| Array Operations | Array Length | Get the number of elements | echo ${#array[@]} |
| Array Elements | Access all elements in an array | echo ${array[@]} |
|
| Adding to Array | Append to an array | array+=(new_value) |
|
| Environment Variables | Define Variable | Set a variable for the current session | export MY_VAR="value" |
| Access Environment Variable | Retrieve the value of a variable | echo $MY_VAR |
|
| List Environment Variables | Display all environment variables | printenv |
|
| Process Management | Run in Background | Run a command in the background | command & |
| Bring to Foreground | Bring background job to foreground | fg %1 |
|
| List Running Jobs | Show background jobs | jobs |
|
| Kill Process | Terminate a running process | kill -9 PID |
|
| Error Handling | Exit Code | Set exit code in scripts | exit 1 |
| Trap Errors | Execute commands on script error | trap "echo Error occurred" ERR |
|
set -e |
Exit script on any error | set -e |
|
| Debugging | set -x |
Print commands as they are executed | set -x |
set +x |
Disable debugging output | set +x |
|
| Debug Specific Section | Enable debugging for specific code blocks | set -x; command; set +x |
|
| Command Substitution | Substitution | Use output of a command as part of another command | today=$(date) |
| Backticks | Alternative way for substitution | `date` |
|
| Regular Expressions | Grep with Regex | Search text with patterns | grep -E "pattern" file.txt |
| Sed for Text Replacement | Replace text in a file | sed 's/old/new/g' file.txt |
|
| Conditional Expressions | String Comparison | Compare strings | [ "$a" = "$b" ] |
| Number Comparison | Compare numbers | [ "$a" -gt "$b" ] |
|
| File Conditions | Check if a file exists, is readable, writable, or executable | [ -f "file.txt" ] |
|
| Advanced Scripting | Sourcing Files | Run another script in the current shell | source file.sh or . file.sh |
| Here Document | Input block to a command | `cat <<EOF | |
| Hello | |||
| EOF` | |||
| Here Strings | Pass string to a command | cat <<< "Hello" |
|
| Job Control | Background and Foreground | Manage background jobs | command & |
| Job Control Commands | jobs, fg, bg for job management |
jobs, fg %1, bg %2 |
|
disown |
Remove job from job table | disown %1 |
|
| Shell Options | set Command |
Configure shell behavior | set -e, set -u, set -x |
shopt Command |
Additional shell options | shopt -s nocaseglob |
|
| Networking Commands | ping |
Check network connection | ping google.com |
curl |
Retrieve data from URLs | curl http://example.com |
|
wget |
Download files from the web | wget http://example.com/file |
|
netstat |
Network connections and ports | netstat -tuln |
|
| Date and Time | date |
Display or set date and time | date "+%Y-%m-%d" |
sleep |
Pause for a specified time | sleep 5 |
|
timeout |
Run a command with a time limit | timeout 10 command |
|
| Archive and Compression | tar |
Archive files | tar -czvf archive.tar.gz dir/ |
gzip |
Compress files | gzip file |
|
unzip |
Decompress files | unzip file.zip |
If you found this cheatsheet helpful, please give this gist a star and follow me on GitHub @Sharique55 for more awesome content!