Environment & shell setup
Why does a command work in one terminal but not another, or on your laptop but not in cron or with sudo? Almost always the answer is the environment: which variables are set, what PATH contains, and which startup files your shell read. This chapter explains all three, plus the aliases and shortcuts that make the shell pleasant to use.
Shell variables vs environment variables
A plain assignment creates a shell variable: only the current shell can see it. export turns it into an environment variable, which is copied into every program the shell starts from then on.
$ GREETING=hello
$ bash -c 'echo "child sees: [$GREETING]"'
child sees: []
$ export GREETING
$ bash -c 'echo "child sees: [$GREETING]"'
child sees: [hello]
$ declare -p GREETING # -x means exported
declare -x GREETING="hello"
$ unset GREETING # remove it again
Two more rules explain a lot of confusion:
DEBUG=1 ./app.shsets the variable for that one command only, without changing your shell.- The copy only goes downwards. A child process can never change its parent's variables, which is why a script that runs
exportorcdhas no effect on your terminal after it finishes. To change the current shell, you source the file instead (see below).
Seeing the environment
$ printenv PATH # one variable
$ printenv | sort | less # all exported variables
$ env | grep -i proxy # env with no arguments also lists them
$ env -i bash --norc # a shell with an (almost) empty environment, for testing
$ set | less # shell variables AND functions too, not just exported ones
Variables you'll meet constantly: HOME (your home folder), USER, PWD (current folder), SHELL (your login shell), EDITOR (used by crontab -e and git commit), LANG (language and character encoding) and PATH.
PATH and how a command is found
When you type python3, bash checks in this order: is it an alias? a shell keyword (if, for)? a function? a builtin (cd, echo, export)? Only then does it search the folders in PATH from left to right and run the first match. If nothing matches: command not found.
type -a shows every match.$ echo "$PATH"
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
$ type ls
ls is aliased to `ls --color=auto'
$ type cd
cd is a shell builtin
$ type python3
python3 is /usr/bin/python3
$ type -a python3 # every match, in PATH order
$ which python3 # searches PATH only
/usr/bin/python3
$ which cd # prints nothing: cd isn't a file, it's built into bash
$ command -v docker # script-friendly "is it installed?" check
Prefer type when debugging "why is the wrong version running?", because it also sees aliases and functions that which can't. Because the first match wins, the order matters: to use your own tools ahead of the system's, add their folder to the front:
export PATH="$HOME/.local/bin:$PATH" # prepend, keep everything that was there
export PATH=~/bin (without :$PATH) replaces the whole list, and suddenly even ls is "command not found". Just open a new terminal, or run export PATH=/usr/local/bin:/usr/bin:/bin to get going again, then fix the line in your startup file.Bash also remembers where it found each command. If you install a new version in a different folder and the old one still runs, hash -r clears that memory. And note that sudo resets most variables and uses its own fixed PATH (secure_path in /etc/sudoers), so tools in ~/.local/bin are "not found" under sudo unless you give the full path.
Startup files: ~/.bashrc vs ~/.profile
Which files bash reads depends on how it was started:
| File | Read by | Put here |
|---|---|---|
~/.profile | login shells: SSH sessions and console logins (Ubuntu's graphical login reads it too) | environment variables and PATH changes |
~/.bashrc | every interactive bash that isn't a login shell, like a new terminal window on a desktop | aliases, functions, prompt, history settings |
/etc/profile, /etc/bash.bashrc | the system-wide versions, read before yours | settings for all users (needs sudo) |
On Ubuntu the default ~/.profile also sources ~/.bashrc, so SSH logins get your aliases too, and it already adds ~/bin and ~/.local/bin to PATH if those folders exist. Scripts (non-interactive shells) read neither file, and Ubuntu's ~/.bashrc stops at its first lines when the shell isn't interactive.
~/.bash_profile exists, login shells read it instead of ~/.profile. Creating one "to add a PATH line" silently disables everything in ~/.profile. On macOS the default shell is zsh, whose files are ~/.zprofile and ~/.zshrc.Sourcing: apply changes now
Editing ~/.bashrc changes nothing in terminals that are already open, because they read it when they started. Re-read it in the current shell with source (or its short form, a dot):
$ source ~/.bashrc
$ . ~/.bashrc # exactly the same thing
Running bash ~/.bashrc or ./file would execute it in a child process, which then exits and takes its settings with it.
Aliases and small functions
alias ll='ls -alF' # Ubuntu's .bashrc already defines ll, la and l
alias k='kubectl'
alias gs='git status'
alias ports='sudo ss -tulpn'
mkcd() { mkdir -p "$1" && cd "$1"; } # functions can take arguments
$ alias # list all aliases
$ unalias k # remove one
$ \ls # run the real ls, skipping the alias
Put them in ~/.bashrc, or in ~/.bash_aliases, which Ubuntu's .bashrc loads automatically if it exists. Aliases are not expanded in scripts, so use full commands (or functions) there.
.env files
Apps usually read secrets and settings from environment variables, and a .env file is a simple list of them kept next to a project:
# .env
DB_HOST=localhost
DB_PORT=5432
API_KEY=change-me
Docker Compose reads a .env file in the project folder automatically, Python has python-dotenv, Node has dotenv, and systemd services can load one with EnvironmentFile=. To load one into your current shell:
$ set -a # auto-export every variable assigned from now on
$ source .env
$ set +a # back to normal
$ echo "$DB_HOST"
localhost
.env file usually contains secrets: add it to .gitignore, give it chmod 600, and commit a .env.example with dummy values instead so others know which variables exist.History tricks and shortcuts
$ history 20 # last 20 commands, numbered
$ !42 # rerun command number 42
$ !! # rerun the last command (sudo !! = again, with sudo)
$ vim /etc/nginx/nginx.conf
$ sudo nginx -t -c !$ # !$ = last argument of the previous command
Ubuntu's .bashrc sets HISTCONTROL=ignoreboth, which skips duplicate lines and any command that starts with a space. Typing a space first is a handy way to keep a command with a password in it out of ~/.bash_history.
| Keys | Does |
|---|---|
| Ctrl+R | search history backwards as you type; Ctrl+R again for older matches, Enter runs it, Ctrl+G cancels |
| Tab / Tab Tab | complete a command or path / list the possibilities |
| Ctrl+A / Ctrl+E | jump to start / end of the line |
| Ctrl+W / Ctrl+U / Ctrl+K | delete the previous word / everything before the cursor / everything after it |
| Ctrl+Y | paste back what the last delete removed |
| Alt+. | insert the last argument of the previous command |
| Ctrl+L | clear the screen |
| Ctrl+C / Ctrl+D | cancel the current command / log out (on an empty line) |
cd - jumps back to the previous folder, which pairs nicely with all of the above.