Raspberry Pi & Linux Guide

I - What is a Raspberry Pi and Linux?

Raspberry Pi

What is it?

The Raspberry Pi is a series of small, affordable, single-board computers developed in the United Kingdom by the Raspberry Pi Foundation in collaboration with Broadcom. It’s designed to promote teaching basic computer science and to provide an accessible platform for hobbyists, educators, and students to explore computing, learn programming, and work on various digital projects.

Raspberry Pi Projects

Raspberry Pi projects range from simple learning tools to complex systems. Some popular project ideas include:

Raspberry Pi Documentation

To read more about the Raspberry Pi, you can visit the official Raspberry Pi website or explore its Wikipedia page for detailed information on its history, models, and specifications. Additionally, there are numerous online communities and forums where Raspberry Pi enthusiasts share their projects and offer support.

Linux

What is Linux?

Why does the Pi use Linux?

II - How to use Linux

Installation

Install the Raspberry Pi Imager on a computer. This is used to install a .iso file to an SD card or MicroSD card (depending on your Raspberry Pi model). Launch the application and you’ll see the following buttons:

Raspberry Pi Imager Interface

Select your Raspberry Pi device and the storage device connected to your computer.

For the Operating System, if you have a Raspberry Pi 3 or newer, the top option should be OK. Anything older, and you should choose Raspberry Pi OS (Legacy, 32-bit) Lite. Note that this will not install a Desktop Environment (DE), which means everything you’ll do is through the terminal. That might sound scary, but don’t worry. This guide will go over everything you need to know to hit the ground running.

Once you hit next, you should see the popup below:

Raspberry Pi Imager Popup

Click EDIT SETTINGS and Set username and password. This is the only setting you should set, but others are available, such as enabling SSH (Secure Shell protocol). For the time being, let’s skip those since they’re not strictly necessary.

Raspberry Pi Settings Edit

Now, wait until the installation is complete!

Raspberry Pi Installation Progress

SSH vs. Local

Using a Raspberry Pi with Linux can be experienced in two distinct ways: through SSH (Secure Shell) or locally by connecting a display directly to the Pi. Here’s a comparison of both methods:

Using SSH:

Using Locally:

If you are going to utilize SSH, please be sure to check that option in the settings page when you are installing, though this can be enabled in the future.

III - The Power of the Linux Terminal

Why use a terminal?

A command is just an application. Some commands open a window (a Graphical User Interface or GUI) while others remain in the terminal (referred to as Command-Line Interface or CLI). Many developers create applications that live in the terminal because, frankly, it’s a lot less work. What this means is that small, specialized tools are widely available on Linux since someone likely has already made it.

While there are many, many more commands, this guide will stick to the essentials to get you up and running quickly. The essentials have been divided into the following categories:

These commands can be accessed in the terminal and can have many different options (called parameters outside of a program, arguments inside a program). Google is your friend here, but an even better friend is tldr. It provides simple and concise explanations of commands with examples for the most common uses of those commands.

Learning these commands will take time. It will at times be frustrating. Like anything worthwhile, it takes time, practice, and patience.

Essential Terminal Commands

Most commands have different parameters, some optional and some required. This guide will only cover the most common uses of the most common commands. Use tldr command to get more uses for a command. Use man command to get detailed information and all parameters for a command.

For most commands, either a full path or relative path may be used for input/output files and directories. Make sure to consider your user access to paths as well. For a command with input and/or output parameters, the input must be a file/directory that your user has access to read. The output must be a file/directory that your user has access to write to.

Most commands also support wildcard characters. Once you’re familiar with commands, start experimenting with wildcards. Start by reading more here.

File Operations

cd

cd is by far the most commonly used command line utility. This changes what directory you are currently in.

Command Description
cd Go to your home directory, /home/username.
cd ~ Go to your home directory, /home/username.
cd /home/username/directory Go to a specific directory by providing a full path.
cd directory Go to a directory that is in your current directory.
ls

ls is the second most used command. This command will list files and directories in your current location by default, but there are multiple options.

Command Description
ls Lists files and directories in your current directory.
ls -l Include more information like ownership and permissions.
ls -la Include hidden files and directories.
ls -la directory List all files and information for a specific directory.
mkdir

mkdir is used to create a new directory or folder, or many directories at once.

Command Description
mkdir a-directory Create a new directory.
mkdir a-directory b-directory ... Make multiple directories.
touch

touch has multiple uses. The primary use is to create new file(s). The secondary use is to update the last-accessed timestamp of a file. Note that this command does not create directories, but will update the timestamp of a directory.

Command Description
touch file.txt Create (or update the access timestamp) a file.
touch file.txt a-directory ... Create/update a file and update a directory.
cp

cp copies a file(s)/directory(ies) to a destination directory. This copies the permissions as well as the file contents themselves. cp writes over any existing output file as well.

Command Description
cp input-file output-file Copy the input file and create/write the output file.
cp a-input b-input directory Copy multiple files into one output directory.
cp -r input-directory output-directory Create a copy of the input directory with the output’s name.
mv

mv moves a file(s)/directory(ies) to a target destination. This can be used to rename a file or directory, or move file(s)/directory(ies) into another location.

Command Description
mv input-file directory Move the input file into the directory.
mv a-input b-input directory Move multiple files into one directory.
mv input-name output-name Rename a directory/file.
rm

rm is the delete command, and can remove one or more files at once, and can be used to delete directories as well.

Command Description
rm input-file Remove a file.
rm a-input b-input Remove multiple files at once.
rm -r a-directory Remove a directory.

Permissions

sudo

sudo allows a command to be run as the root user (see II - How to use Linux). This is most commonly used in conjunction with your package manager (see Installing Applications), but there are many use cases where you’ll want to use it. From editing system configuration files to executing system commands, in Windows terms sudo elevates your command to be run as the Administrator.

Related: su

Association: switch user and do || super user and do

Command Description
sudo nvim /usr/local/bin/a-custom-script Since a regular user doesn’t have permission to edit a file in /usr/local/bin, switch to the root user to edit the file.
sudo apt install firefox Installing, updating, upgrading, and removing packages requires sudo (see Apps).
sudo cp new-script /usr/local/bin Copy a new script to a globally accessible script location (see IV - Making your own CLI tools).

Apps

Package Manager == App Store

A package manager is an app store (in coding, the ‘==’ operation is a boolean expression meaning the left and right are the same value). There are a few important differences though.

Raspberry Pi

For the Raspberry Pi, the package manager is Advanced Package Tool, commonly called apt. Packages are applications, with all dependencies and instructions already set up.

The install and upgrade sub-commands will typically require some input from you. This comes in the form of simple Y or N prompts typically.

Command Description
sudo apt update Check if any packages have a new version available.
sudo apt install firefox Install the Firefox web browser.
sudo apt remove firefox Uninstall the Firefox web browser.
sudo apt upgrade Upgrade every package installed with apt to the latest version.
apt search firefox Find a package based upon search criteria.

Coding

Linux is a programmer’s playground. Writing code that will modify your system, create applications, and CLI tools, are all easily accessible through Linux. This section will cover how you can write code in the terminal, and how you can run that code.

Text Editor

NeoVim

High-level, Neovim is a customizable and extensible text editor. You can either install a pre-configured Neovim distro (like LunarVim, AstroNvim, or LazyVim) or start from scratch. While you’re learning, a pre-configured distro is going to smooth the learning curve and is the general recommendation for starting out with Neovim. It’ll include modern conveniences like auto-complete, GitHub Copilot, warnings and errors, and more.

Eventually, creating a custom configuration is ideal but ultimately not necessary. The keybindings below are the same across distributions. Additionally, most servers will have at least Vi (an ancestor of Neovim) installed. Part of the power of Neovim (and its ancestors Vi and Vim) is the modal interface. Fancy words aside, this just means that you only operate within different modes. In different modes, the keybindings change. This will only cover the most common and necessary keybinds and commands.

Command Description Category
nvim Open a new file. The file is created with its contents once you save. Basic file creation
nvim file.txt Open a file called file.txt. Open a file
nvim . Open the current directory in Neovim, using netrw. Enter netrw
nvim a-directory Open a directory from a path, using netrw. Enter netrw
Keybinds:

Part of the power of Neovim is repeatable commands. The commands below can have a number prefix to indicate how many times to perform that command. Eg. 50j in command mode translates to moving 50 lines down.

Keybind Description Category
h Move the cursor left a column, but in the same row. Navigation
j Move the cursor down a row, and attempt to preserve the column. Navigation
k Move the cursor right a column, but in the same row. Navigation
l Move the cursor up a row, and attempt to preserve the column. Navigation
w Move the cursor to the start of the next word or special character, ignoring whitespace. Navigation
b Move the cursor to the start of the previous word or special character, ignoring whitespace. Navigation
i Enter insert mode, the primary typing mode. Insert Mode
I Enter insert mode at the start of the current line. Insert Mode
S Enter insert mode after clearing the current line. Insert Mode
A Enter insert mode at the end of the line. Insert Mode
v Enter visual mode (highlighting/selecting) at the cursor’s current location. Select text with navigation keys. Visual Mode
V Enter visual mode at the cursor’s current row. j and k are used to select more rows. Visual Mode
y Copy highlighted text to Neovim’s clipboard. NOTE: Neovim’s clipboard is separate from your system clipboard. Visual Mode
"*y Copy highlighted text to your system clipboard. Visual Mode
u Undo. Special Function
p Paste text from Neovim’s clipboard. Special Function
:Ex Enter Neovim’s file explorer, netrw. Enter netrw
% Create a file inside the current directory. netrw keybinds
d Create a new directory inside the current directory. netrw keybinds
D Delete a file or empty directory. netrw keybinds
:w {filename} Write (save) the current file. You can specify a filename as well. File Management
:q Quit (exit without saving) the current file. File Management
:wq Write (save) and quit (exit) the current file. File Management
:%s/original/new/g The most common command I use, a highly and easily configurable search and replace. The (optional) % means the entire file. By default, it’ll only apply to the current line. original is the current text and new is the replacement. The (optional) g means every instance on each line. By default, it’ll only apply to the first occurrence. Advanced Command
Escape Exit current mode. Exit mode

Nano - TODO

Setting Up Programming Languages

A broad overview on a handful of languages that you can use with the Raspberry Pi:

Python is the most commonly used language with the Raspberry Pi. Python is known for its syntactic simplicity for novice programmers...

Python

  1. Run sudo apt install python.
  2. Verify the installation was successful with python --version.
  3. Verify that the python package manager was installed with pip --version.

Git Essentials

Git is a critical component of modern software development...

git clone

Command Description
git clone https://github.com/<user>/<repo> Create a local copy of the remote repo owned by <user> called <repo>.
git clone <remote> <destination> Clone a remote repository and save it in a directory called <destination>.

git stage

Command Description
git stage -A Include all changes in the commit.
git stage <file> Add a file you want to include in the commit.

git commit

Command Description
git commit Open your default text editor to create the commit message. Once you save and quit, a new snapshot of your local repo is saved.
git commit -m “A commit message.” Create the snapshot with a commit message.
git commit --all This option auto-stages your changes for the commit, so you do not need git stage.

git push

git push will attempt to upload your commit(s) to the remote repository.

git pull

git pull will download the latest changes from the remote repository.

Quality of Life Improvements

man

man is used to open instructional information about a particular command, application, or function. The man command is quite powerful, though a touch verbose. It’ll provide information on all possible parameters, uses, and idiosyncrasies.

Command Description
man <command> Open the manual for a command, application, or function. Press q to quit, and use j and k to move down and up respectively.

tldr

tldr is the concise version of man. Personally, I use tldr almost every day. It provides the most common few uses of a command, application, or function.

Command Description
tldr <command> Get quick information about a command, application, or function.

zsh

zsh is a shell, effectively the programming language your terminal uses. zsh has more customization options available, such as oh-my-zsh, starship, and much more. Using your programming skills to customize your operating system is a deep rabbit-hole that you should at least be aware of.

IV - How to unleash the Raspberry Pi’s Potential.

Here is an example script (found here) which gets your Raspberry Pi setup with some common services.

        
            #!/bin/bash

            # This script gets a Raspberry Pi setup with essential applications.
            #
            # For explanations of commands, visit raspi.vintagecoding.net

            # GLOBAL VARIABLES
            DOMAIN=""
            MANUAL_PORT=5090
            JELLYFIN_PORT=5091
            OLLAMA_PORT=5092

            # This function initializes core services and packages for getting started.
            init() {
                # Update repositories and upgrade installed packages.
                sudo apt update && sudo apt upgrade;

                # Install requisite packages for cloudflared.
                sudo apt install curl lsb-release;

                # Add cloudflare gpg key
                sudo mkdir -p --mode=0755 /usr/share/keyrings
                curl -fsSL https://pkg.cloudflare.com/cloudflare-main.gpg | sudo tee /usr/share/keyrings/cloudflare-main.gpg > /dev/null

                # Add this repo to your apt repositories
                echo 'deb [signed-by=/usr/share/keyrings/cloudflare-main.gpg] https://pkg.cloudflare.com/cloudflared any main' | sudo tee /etc/apt/sources.list.d/cloudflared.list

                # install cloudflared
                sudo apt-get update && sudo apt-get install cloudflared

                # Install cloudflared.
                # Install podman, a container technology for easily deploying projects.
                # Install golang, a server-side programming language.
                # Install tools for the user
                sudo apt update;
                sudo apt install cloudflared podman golang tldr neovim;

                # Get user input for some default applications to get started.
                read -p "Do you want a mirror of the manual from raspi.vintagecoding.net on this device? (y/N): " MANUAL;
                MANUAL=$(echo "$MANUAL" | tr '[:upper:]' '[:lower:]')
                if [[ -z "$MANUAL" || "$MANUAL" == "n" ]]; then
                    MANUAL="n"
                else
                    init_manual;
                fi

                read -p "Do you want to setup Jellyfin, a personal Netflix alternative? (y/N): " JELLYFIN;
                JELLYFIN=$(echo "$JELLYFIN" | tr '[:upper:]' '[:lower:]')
                if [[ -z "$JELLYFIN" || "$JELLYFIN" == "n" ]]; then
                    JELLYFIN="n"
                else
                    init_jellyfin;
                fi

                read -p "Do you want to setup Ollama, a personal ChatGPT alternative? (y/N): " OLLAMA;
                OLLAMA=$(echo "$OLLAMA" | tr '[:upper:]' '[:lower:]')
                if [[ -z "$OLLAMA" || "$OLLAMA" == "n" ]]; then
                    OLLAMA="n"
                else
                    init_ollama;
                fi

            }

            # This function initializes the manual mirror of raspi.vintagecoding.net
            init_manual() {
                cd ~/ras-pi/man/pages;

                # This creates what's called a systemd service. These are processes that you create which can start after a reboot.
                echo "[Unit]
                Description=Raspberry Pi Manual Mirror
                After=network.target
                StartLimitIntervalSec=0

                [Service]
                Type=simple
                Restart=always
                RestartSec=1
                User=$(whoami)
                WorkingDirectory=$(pwd)
                ExecStartPre=/usr/bin/git pull
                ExecStart=/usr/bin/python3 -m http.server $MANUAL_PORT

                [Install]
                WantedBy=multi-user.target" | sudo tee /etc/systemd/system/manual.service;

                sudo systemctl enable manual.service;
                sudo systemctl start manual.service;
                sudo systemctl daemon-reload;
            }

            # This function initializes Jellyfin.
            init_jellyfin() {
                # Get the official image of Jellyfin software
                podman pull ghcr.io/jellyfin/jellyfin;

                echo "Making media directories where Jellyfin will retrieve content.";
                echo "It is up to you to provide supported files and build a library.";

                cd;
                mkdir media;

                podman run \
                    --detach \
                    --label "io.containers.autoupdate=registry" \
                    --name myjellyfin \
                    --publish $JELLYFIN_PORT:8096/tcp \
                    --user $(id -u):$(id -g) \
                    --volume jellyfin-cache:/cache:Z \
                    --volume jellyfin-config:/config:Z \
                    --mount type=bind,source=/$HOME/media,destination=/media,ro=true,relabel=private \
                    --restart always \
                ghcr.io/jellyfin/jellyfin;

                echo "Finished creating the Jellyfin container! It is now live on";
                echo "http://localhost:$JELLYFIN_PORT. If you enabled it, it'll also be";
                echo "available at media.yourdomain.com.";
            }

            # This function initializes Ollama.
            init_ollama() {
                echo "This will take a while...";

                cd;
                curl -fsSL https://ollama.com/install.sh | sh;
                export OLLAMA_BASE_URL=http://localhost:11434;

                read -p "Do you want to require a login for your AI? (n/Y): " REQUIRE_LOGIN;
                REQUIRE_LOGIN=$(echo "$REQUIRE_LOGIN" | tr '[:upper:]' '[:lower:]')
                if [[ -z "$REQUIRE_LOGIN" || "$REQUIRE_LOGIN" == "n" ]]; then
                    export WEBUI_AUTH=False;
                fi

                source $HOME/.bashrc

                # TODO: Write a script so this can be daemonized.
                python -m venv open-webui-env;
                source open-webui-env/bin/activate
                pip install open-webui;

                echo "server {
                    listen 80; #or whatever port your open-webui backend is running on.
                    server_name localhost;

                    location / {
                        proxy_pass http://localhost:$OLLAMA_PORT/;
                        proxy_http_version 1.1;
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection 'upgrade';
                        proxy_set_header Host $host;
                        proxy_cache_bypass $http_upgrade;
                    }
                    location /api/ {
                        proxy_pass http://localhost:$OLLAMA_PORT/api/; # Ensure the trailing slash is present
                        proxy_http_version 1.1;
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection 'upgrade';
                        proxy_set_header Host $host;
                        proxy_cache_bypass $http_upgrade;
                    }
                }" | sudo tee/etc/nginx/sites-available/open-webui;
                sudo ln -s /etc/nginx/sites-available/open-webui /etc/nginx/sites-enabled
                sudo systemctl enable nginx;
                sudo systemctl start nginx;

                open-webui serve --port $OLLAMA_PORT &
            }

            init;