Shell Script Cheat Sheet

This cheat sheet can serve as a quick reference to some of the most commonly used shell scripting commands and structures.

Basic Commands

  • echo "Hello World": Print text to the console.
  • read varname: Read input from the user and store it in varname.
  • export VARNAME=value: Set environment variable VARNAME to value.
  • pwd: Print the current working directory.
  • cd directory: Change the current directory to directory.
  • ls: List directory contents.
  • cp source destination: Copy files from source to destination.
  • mv source destination: Move files from source to destination.
  • rm file: Remove a file.

Variables

  • VAR="value": Define a variable.
  • $VAR: Access the value of a variable.
  • ${VAR}: Also used to access a variable, useful in complex strings.

Conditional Statements

If Statement

if [ condition ]; then
    # commands
elif [ condition ]; then
    # commands
else
    # commands
fi

Case Statement

case $variable in
    pattern1)
        # commands
        ;;
    pattern2)
        # commands
        ;;
    *)
        # default commands
        ;;
esac

Loops

For Loop

for var in list; do
    # commands
done

While Loop

while [ condition ]; do
    # commands
done

Functions

function_name () {
    # commands
}

File Testing

  • -f file: True if the file exists and is a regular file.
  • -d directory: True if the directory exists.
  • -e path: True if the path exists.
  • -r file: True if the file is readable.
  • -w file: True if the file is writable.
  • -x file: True if the file is executable.

Debugging

  • set -x: Enable debugging.
  • set +x: Disable debugging.

Subscribe to dadonk

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe