Mastering Bash: Your Ultimate Cheat Sheet with Examples for Unix-based Systems

Basic Commands:

  • cd: Change directory
    • Example: cd Documents (Change to the “Documents” directory)
  • ls: List files and directories
    • Example: ls -l (List files and directories in long format)
  • pwd: Print working directory
    • Example: pwd (Display the current directory)
  • mkdir: Create a directory
    • Example: mkdir new_dir (Create a directory named “new_dir”)
  • rm: Remove files or directories
    • Example: rm file.txt (Remove a file named “file.txt”)
    • Example: rm -r dir/ (Remove a directory named “dir” and its contents)
  • cp: Copy files and directories
    • Example: cp file.txt new_file.txt (Copy “file.txt” to “new_file.txt”)
  • mv: Move or rename files and directories
    • Example: mv file.txt new_dir/ (Move “file.txt” to “new_dir/”)
    • Example: mv old_name.txt new_name.txt (Rename “old_name.txt” to “new_name.txt”)
  • cat: Concatenate and display file contents
    • Example: cat file.txt (Display the contents of “file.txt”)
  • touch: Create an empty file or update timestamp
    • Example: touch new_file.txt (Create an empty file named “new_file.txt”)
  • echo: Print a message or variable
    • Example: echo "Hello, World!" (Print the message “Hello, World!”)
    • Example: echo $PATH (Print the value of the “PATH” environment variable)

File Permissions:

  • chmod: Change file permissions
    • Example: chmod +x script.sh (Grant execute permission to “script.sh”)
    • Example: chmod 644 file.txt (Set read and write permissions for the owner, and read permissions for others on “file.txt”)
  • chown: Change file ownership
    • Example: chown user:group file.txt (Change the owner and group of “file.txt” to “user” and “group” respectively)

File Manipulation:

  • grep: Search for a pattern in files
    • Example: grep "pattern" file.txt (Search for “pattern” in “file.txt”)
  • sed: Stream editor for text manipulation
    • Example: sed 's/old/new/g' file.txt (Replace all occurrences of “old” with “new” in “file.txt”)
  • wc: Count lines, words, and characters in a file
    • Example: wc -l file.txt (Count the number of lines in “file.txt”)

Scripting:

  • Variables: Assign and use variables
    • Example: name="John"; echo "Hello, $name!" (Assign “John” to the variable “name” and print a message using the variable)
  • if-else: Conditional statements
    • Example: if [ $num -gt 10 ]; then echo "Greater than 10" else echo "Less than or equal to 10" fi (Check if the variable “num” is greater than 10 and print the appropriate message)
    • for loop: Iterate over a sequence
      • Example: for i in {1..5}; do echo "Number: $i" done (Iterate from 1 to 5 and print the number in each iteration)
    • while loop: Execute commands while a condition is true
      • Example:num=1 while [ $num -le 5 ]; do echo "Number: $num" num=$((num + 1)) done (Print numbers from 1 to 5 using a while loop)
    • Functions: Define and use functions
      • Example:greet() { echo "Hello, $1!" } greet "John" (Define a function called “greet” that takes a parameter and greets the person)
    • Command substitution: Use command output as a variable
      • Example:date=$(date +%Y-%m-%d) echo "Today's date is: $date" (Assign the current date to the variable “date” using command substitution)

Input and output redirection:

  • Example:command > output.txt (Redirect the output of a command to a file)
  • Pipes: Connect the output of one command to the input of another
    • Example:cat file.txt | grep "pattern" (Search for a pattern in the contents of a file using pipes)
  • Command line arguments: Access arguments passed to a script
    • Example:echo "The script name is: $0" echo "First argument: $1" echo "Second argument: $2" (Print the script name, along with the first and second arguments)

Conditional Expressions:

  • [[…]]: Extended test command with advanced conditionals
    • Example:if [[ $num -gt 10 && $num -lt 20 ]]; then echo "Number is between 10 and 20" fi (Check if the variable “num” is greater than 10 and less than 20)
  • case: Execute commands based on pattern matching
    • Example:case $option in "a") echo "Option A selected" ;; "b") echo "Option B selected" ;; *) echo "Invalid option" ;; esac (Execute different commands based on the value of the variable “option”)

Command Line Tools:

  • find: Search for files and directories in a directory hierarchy
    • Example:find . -name "*.txt" (Find all files with the extension “.txt” in the current directory and its subdirectories)
  • grep: Search for a pattern in files
    • Example:grep "pattern" file.txt (Search for the pattern “pattern” in the file “file.txt”)
  • awk: Text processing tool for extracting data and generating reports
    • Example:bashCopy codeawk '{print $1}' file.txt (Print the first field of each line in “file.txt”)
  • sort: Sort lines of text files
    • Example:sort file.txt (Sort the lines in “file.txt” in ascending order)
  • cut: Extract specific columns from a file
    • Example:cut -d "," -f 1,3 file.csv (Extract the first and third columns from a CSV file, assuming comma as the delimiter)

Shell Variables and Environment:

  • $HOME: Home directory
    • Example: cd $HOME (Change to the user’s home directory)
  • $USER: Current user’s username
    • Example: echo "Hello, $USER!" (Print a personalized greeting for the current user)
  • $PATH: Colon-separated list of directories to search for executable files
    • Example: echo $PATH (Display the current value of the PATH variable)

File Compression and Archiving:

  • tar: Archive files into a tarball
    • Example:tar -cvf archive.tar file1.txt file2.txt (Create a tarball named “archive.tar” containing “file1.txt” and “file2.txt”)
  • gzip: Compress files using the gzip algorithm
    • Example:gzip file.txt (Compress “file.txt” and create “file.txt.gz”)
  • gunzip: Decompress gzip files
    • Example:gunzip file.txt.gz (Decompress “file.txt.gz” and restore the original “file.txt”)

Process Management:

  • ps: Report a snapshot of current processes
    • Example: ps aux (Display a detailed list of all running processes)
  • kill: Terminate a process by its process ID (PID)
    • Example: kill 1234 (Terminate the process with PID 1234)
  • top: Monitor system processes in real-time
    • Example: top (Display the current CPU and memory usage, along with the list of processes)
  • bg: Move a suspended process to the background
    • Example:sleep 10 # Press Ctrl + Z to suspend the process bg # Move the suspended process to the background
  • fg: Bring a background process to the foreground
    • Example:sleep 10 & # Start a process in the background fg # Bring the background process to the foreground

Text Manipulation:

  • tr: Translate or delete characters
    • Example: echo "Hello" | tr 'el' 'XY' (Translate ‘e’ to ‘X’ and ‘l’ to ‘Y’ in the word “Hello”)
  • head: Output the first part of files
    • Example: head -n 5 file.txt (Display the first 5 lines of “file.txt”)
  • tail: Output the last part of files
    • Example: tail -n 10 file.txt (Display the last 10 lines of “file.txt”)
  • sort: Sort lines of text files
    • Example: sort file.txt (Sort the lines of “file.txt” in lexicographic order)
  • uniq: Report or omit repeated lines
    • Example: uniq file.txt (Remove consecutive duplicate lines from “file.txt”)

Networking:

  • ping: Send ICMP echo requests to a network host
    • Example: ping google.com (Send ICMP echo requests to “google.com”)
  • ifconfig: Configure and display network interface parameters
    • Example: ifconfig eth0 (Display details of the “eth0” network interface)
  • ssh: Securely connect to a remote machine
    • Example: ssh user@hostname (Establish an SSH connection to “hostname” as “user”)
  • Job Control:
  • jobs: List active jobs and their status
    • Example: jobs (Display a list of currently running jobs)
  • Ctrl + C: Interrupt the current foreground process
    • Example: Pressing Ctrl + C in the terminal terminates the currently running command
  • Ctrl + Z: Suspend the current foreground process
    • Example: Pressing Ctrl + Z in the terminal suspends the currently running command
  • nohup: Run a command immune to hangups, even if the terminal is closed
    • Example: nohup command & (Run “command” in the background, ignoring hangup signals)

Environment Variables:

  • export: Set an environment variable
    • Example: export VAR_NAME=value (Set the environment variable “VAR_NAME” with the value “value”)
  • $PATH: Environment variable containing the directories to search for executable files
    • Example: echo $PATH (Display the current value of the PATH variable)
  • $HOME: Environment variable representing the user’s home directory
    • Example: cd $HOME (Change to the user’s home directory)

Process Control:

  • &: Run a command in the background
    • Example: command & (Run “command” in the background)
  • ctrl+z: Suspend the current foreground process
    • Example: Pressing Ctrl + Z in the terminal suspends the currently running command
  • jobs: List active jobs and their status
    • Example: jobs (Display a list of currently running jobs)
  • fg: Bring a background process to the foreground
    • Example: fg %1 (Bring the first background job to the foreground)
  • bg: Resume a suspended background process
    • Example: bg %1 (Resume the first suspended background job)

Shell Scripting:

  • #!/bin/bash: Shebang line specifying the shell to execute the script
    • Example: #!/bin/bash (Place this line at the beginning of a script to specify Bash as the interpreter)
  • $0: Special variable representing the script’s name
    • Example: echo "Script name: $0" (Print the name of the script)
  • $1, $2, …: Positional parameters representing command-line arguments
    • Example: echo "First argument: $1" (Print the first command-line argument)
  • $@: All the command-line arguments as separate strings
    • Example: for arg in "$@"; do echo "Argument: $arg"; done (Print all command-line arguments)
  • $#: Number of command-line arguments
    • Example: echo "Number of arguments: $#"

Input and Output:

  • stdin, stdout, stderr: Standard input, output, and error streams
    • Example: command < input.txt (Redirect the contents of “input.txt” as input to the command)
    • Example: command > output.txt (Redirect the command’s output to “output.txt”)
    • Example: command 2> error.txt (Redirect the command’s error output to “error.txt”)
  • tee: Read from standard input and write to standard output and files
    • Example: command | tee output.txt (Pass the output of “command” to both the standard output and “output.txt”)

System Information:

  • uname: Print system information
    • Example: uname -a (Print all system information, including the kernel version)
  • uptime: Display system uptime and load average
    • Example: uptime (Display the system’s uptime and load average)
  • free: Display memory usage
    • Example: free -h (Display memory usage in a human-readable format)
  • df: Report file system disk space usage
    • Example: df -h (Display disk space usage in a human-readable format)

Process Monitoring:

  • ps: Report a snapshot of current processes
    • Example: ps aux (Display a detailed list of all running processes)
  • top: Monitor system processes in real-time
    • Example: top (Display the current CPU and memory usage, along with the list of processes)
  • htop: Interactive process viewer (requires installation)
    • Example: htop (Launch the interactive process viewer)
  • File Searching:
  • locate: Find files by name
    • Example: locate myfile.txt (Find the file named “myfile.txt” on the system)
  • find: Search for files and directories based on various criteria
    • Example: find /path/to/search -name "*.txt" (Find all files with the extension “.txt” in the specified directory and its subdirectories)
  • Network Operations:
  • curl: Transfer data from or to a server
    • Example: curl http://example.com (Retrieve the content of a web page)
  • wget: Download files from the web
    • Example: wget http://example.com/file.txt (Download the file “file.txt” from a web server)

Conditional Execution:

  • &&: Execute the next command if the previous command succeeds
    • Example: command1 && command2 (Run “command2” only if “command1” succeeds)
  • ||: Execute the next command if the previous command fails
    • Example: command1 || command2 (Run “command2” only if “command1” fails)

Command Substitution:

  • $(command): Substitute the output of a command
    • Example: echo "Today is $(date)" (Print the current date using the “date” command)
  • command: (Backticks) Substitute the output of a command (older syntax)
    • Example: echo "Today is date" (Print the current date using the “date” command)

Advanced Bash Scripting:

  • Arrays: Store multiple values in a single variable
    • Example:my_array=("value1" "value2" "value3") echo "${my_array[0]}" # Access the first element echo "${my_array[@]}" # Print all elements

Command History:

  • history: Display a list of previously executed commands
    • Example: history (Display a list of recently executed commands)
  • !!: Repeat the last executed command
    • Example: !! (Execute the last command again)
  • !n: Repeat the nth command in the history
    • Example: !42 (Execute the 42nd command in the history)
  • !string: Repeat the most recent command starting with “string”
    • Example: !ls (Execute the most recent command starting with “ls”)

Debugging and Profiling:

  • set -x: Enable debugging mode
    • Example: set -x (Enable debugging mode, displaying each command before executing it)
  • strace: Trace system calls and signals
    • Example: strace command (Trace system calls made by “command”)
  • time: Measure the execution time of a command
    • Example: time command (Measure the execution time of “command”)