Linux & the Command Line

Environment, Shell Configuration and Your First Script

35 min

Environment variables

Programs read settings from environment variables. This is how PandaDev reads DATABASE_URL and SECRET_KEY on Render.

echo $HOME
echo $PATH
export APP_ENV=staging       # set for this shell and its children
env | grep APP_              # list matching variables
unset APP_ENV
APP_ENV=test python app.py   # set for one command only

PATH: how the shell finds programs

PATH is a colon-separated list of folders. When you type python, the shell searches them in order.

which python                 # which one will run?
export PATH="$HOME/.local/bin:$PATH"   # add a folder at the front

"command not found" usually means the program is not installed, or its folder is not in PATH.

Making settings permanent

Add lines to ~/.bashrc (Bash) or ~/.zshrc (Zsh), then reload:

echo 'alias ll="ls -lah"' >> ~/.bashrc
echo 'export EDITOR=nano' >> ~/.bashrc
source ~/.bashrc

Useful aliases:

alias ll='ls -lah'
alias gs='git status'
alias ..='cd ..'

Never put secrets in .bashrc on shared machines. Use a .env file with 600 permissions, or the platform's secret store.

Your first script

Create backup-notes.sh:

#!/usr/bin/env bash
set -euo pipefail

SRC="$HOME/notes"
DEST="$HOME/backups"
STAMP=$(date +%Y-%m-%d_%H%M)

mkdir -p "$DEST"
tar -czf "$DEST/notes-$STAMP.tar.gz" -C "$SRC" .
echo "Saved $DEST/notes-$STAMP.tar.gz"

# keep only the 7 newest backups
ls -1t "$DEST"/notes-*.tar.gz | tail -n +8 | xargs -r rm --

Run it:

chmod +x backup-notes.sh
./backup-notes.sh

What each line does:

  • #!/usr/bin/env bash (the shebang) says which interpreter runs the file.
  • set -euo pipefail stops on errors, on unset variables and on failures inside pipes. Start every script with it.
  • Variables are quoted ("$DEST") so paths with spaces work.
  • $(...) runs a command and inserts its output.

The Automation & Scripting track builds on this with arguments, functions, loops, error handling and scheduling.

Practice

In the Practice Terminal, run export NAME=panda, then echo "Hello $NAME". Complete the First commit mission to preview the Git track.

Check yourself

  • Where would you add a folder so its programs run without a full path?
  • Why should every script begin with set -euo pipefail?
  • What is the difference between VAR=x cmd and export VAR=x?

Votre progression est enregistrée dans ce navigateur uniquement.

Envoyer pour relecture (10 points)