Skip to content
Home » Bash Scripting Cheat Sheet

Bash Scripting Cheat Sheet

Bash Basics

  • #!/bin/bash: Shebang to specify the shell used for the script
  • echo "text": Print a message to the terminal
  • ls: List the contents of the current directory
  • cd /path/to/directory: Change to a different directory
  • pwd: Print the current working directory

Variables

  • variable="value": Assign a value to a variable
  • echo $variable: Print the value of a variable
  • $1, $2, etc.: Command line arguments
  • $#: Number of command line arguments
  • $@: All command line arguments
  • $?: Exit status of the last command

Conditionals

  • if [ condition ]; then ... fi: If statement
  • else: Else statement
  • elif: Else if statement
  • -eq, -ne, -lt, -le, -gt, -ge: Comparison operators
  • &&, ||: Logical operators

Loops

  • for variable in list; do ... done: For loop
  • while [ condition ]; do ... done: While loop

Files

  • touch file.txt: Create an empty file
  • cat file.txt: Display the contents of a file
  • echo "text" > file.txt: Overwrite a file with text
  • echo "text" >> file.txt: Append text to a file
  • cp source destination: Copy a file
  • mv source destination: Move or rename a file
  • rm file.txt: Remove a file

Miscellaneous

  • sleep n: Pause for n seconds
  • chmod +x script.sh: Make a script executable
  • source script.sh or ./script.sh: Execute a script

Note: This cheat sheet is intended as a quick reference and does not cover all aspects of bash scripting. It is important to consult the manual pages or other resources for more information and guidance.

Leave a Reply

Your email address will not be published. Required fields are marked *

nine + twenty =