Bash

Bash Scripting Cheatsheet

Variables

  • Declare a variable: variable_name=value
  • Access the value of a variable: $variable_name

Conditionals

  • If statement:
    if [ condition ]; then
      # code to execute if condition is true
    else
      # code to execute if condition is false
    fi

Loops

  • For loop:

    for item in list; do
      # code to execute for each item in the list
    done
  • While loop:

    while [ condition ]; do
      # code to execute while condition is true
    done

Functions

  • Declare a function:

    function_name() {
      # code to execute
    }
  • Call a function: function_name

Input/Output

  • Read user input: read variable_name
  • Print to standard output: echo "message"

File Operations

  • Check if a file exists: if [ -f file_path ]; then ...
  • Create a new file: touch file_path
  • Delete a file: rm file_path

Command Line Arguments

  • Access command line arguments: $1, $2, …

Error Handling

  • Exit the script with an error code: exit error_code
  • Handle errors with trap:
    trap "error_handling_function" ERR

Comments

  • Single-line comment: # comment

  • Multi-line comment:

    : '
    This is a
    multi-line comment
    '

    Logical Operators

    • AND operator (&&): Execute the next command only if the previous command succeeds.
    • OR operator (||): Execute the next command only if the previous command fails.
    • Example:
      command1 && command2
      In the above example, command2 will only be executed if command1 succeeds.
      command1 || command2
      In the above example, command2 will only be executed if command1 fails.

    Chaining Commands

    • Use semicolon (;) to chain multiple commands on the same line.
    • Example:
      command1 ; command2 ; command3
      In the above example, command1, command2, and command3 will be executed sequentially.

    Controlling Flow of Commands

    • Use the if statement to control the flow of commands based on conditions.
    • Example:
      if [ condition ]; then
        # code to execute if condition is true
      else
        # code to execute if condition is false
      fi
      In the above example, the code inside the if block will be executed if the condition is true. Otherwise, the code inside the else block will be executed.

For more information, refer to the Bash documentation.