# Shell basics: PATH, variables, streams and sudo

How the shell finds commands, how variables and dotfiles shape every session, where output and errors go, and how to use root power without hurting yourself.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 3. About 35 minutes, beginner. Source: https://devops.rajeev.pro/courses/linux/03-shell-basics

## What you will learn

- Explain how the shell finds a command, and fix "command not found"
- Get help for any command in seconds with man, --help and type
- Set, export and persist environment variables, and know which dotfile to use
- Send output and errors where you want with >, >>, 2>, 2>&1, | and tee
- Use sudo safely and explain why you shouldn't work as root

## Getting help fast

Before every command had searchable web documentation, administrators relied on the manuals installed on the
server. That is still useful when the network is down or the server's software version differs from a web
page. Instead of memorising every option, learn how to find the local command's help quickly.

`--help` gives a short summary; `man` opens the full manual. Manual sections separate commands from file
formats and administrator tools. `type` tells you whether a name resolves to an alias, function, builtin or
external program, so you know which documentation applies.

Use these commands to find the answer on the machine you're operating:

```sh
$ ls --help | less           # short summary of options, built into most commands
$ man ls                     # the full manual. /word searches, n next match, q quits
$ man 5 crontab              # section 5: the crontab FILE format, not the command (section 1)
$ man -k password            # search all manual pages for a word (same as apropos)
$ type cd                    # what kind of command is this?
cd is a shell builtin
```

Manual sections you'll meet: **1** commands, **5** file formats (`/etc/fstab`, `crontab`), **8**
admin commands (`useradd`, `sshd`). When a command has no `man` page, try `help` (for bash
builtins, such as `help cd`) or `command --help`.

Search with `/word` inside `man`, press `n` for the next match, and `q` to leave. If a manual page is missing,
check the package that provides the command or use its built-in help. A common mistake is reading `man
crontab` when you need the file format; `man 5 crontab` describes that format, while `man 1 crontab` covers
the command.

## How the shell finds a command

When you type `grep error app.log`, bash has to decide what `grep` is. It checks, in order:

> **Figure.** How bash finds a command: first aliases, then shell functions, then builtins such as cd and echo, then each directory in PATH from left to right. The first match runs. If nothing matches, bash prints command not found.
>
> The first match wins. That's why order in $PATH matters.

```sh
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
$ type grep ls cd
grep is /usr/bin/grep
ls is aliased to `ls --color=auto'
cd is a shell builtin
$ which python3              # the file PATH would run
/usr/bin/python3
$ ./deploy.sh                # not in PATH? Give the path yourself
```

`cd` has to be a builtin: a separate program could only change its own folder, not your shell's.

"Command not found" means one of three things: a typo, the program isn't installed, or it's
installed in a folder that isn't in `PATH`. Check with `type name` or `ls` the folder you expect.

> **Video.** [Everything You Need to Know About $PATH in Bash](https://www.youtube.com/watch?v=rJMFxIbDe-g) (tutoriaLinux)

## Variables and the environment

Commands often need settings such as an environment name or a path to a config file. A **shell variable** is
private to the current shell until exported. An **environment variable** is copied into child processes when
they start. This lets a deployment script receive settings without hard-coding them, but it also means every
child process can inherit sensitive values.

```sh
$ APP_ENV=staging            # a shell variable: this shell only. No spaces around =
$ echo "$APP_ENV"
staging
$ bash -c 'echo "[$APP_ENV]"'  # a child process can't see it
[]
$ export APP_ENV             # now it's an environment variable, inherited by children
$ bash -c 'echo "[$APP_ENV]"'
[staging]
$ env | grep APP_ENV         # every environment variable
APP_ENV=staging
$ unset APP_ENV              # remove it
$ APP_ENV=prod ./deploy.sh   # set it for ONE command only
```

Every program you start gets a **copy** of the environment. That's how `PATH`, `HOME`, `USER`,
`LANG` and your app's settings reach it, and why changing a variable in one terminal doesn't
change it in another.

Use a temporary assignment such as `APP_ENV=prod ./deploy.sh` when only one process needs the value. Export
it when child commands in the current shell need it. Unset secrets when they are no longer needed, and avoid
putting them in shell startup files or command lines that other users can inspect. A common mistake is
expecting a shell variable to reach a child process without `export`.

### Quoting

| You write                     | Bash does                                                      |
| ----------------------------- | -------------------------------------------------------------- |
| `echo "$HOME/logs"`           | expands variables: `/home/rajeev/logs`                         |
| `echo '$HOME/logs'`           | nothing: prints `$HOME/logs` literally                         |
| `echo "Today is $(date +%A)"` | runs the command inside `$( )` and inserts its output          |
| `rm "$FILE"`                  | always quote variables: a name with a space stays one argument |

### Making it permanent: the dotfiles

Variables, aliases and `PATH` changes vanish when the shell closes. To keep them, put them in a
file bash reads at start-up:

| File                                | Read by                   | Put here                                                       |
| ----------------------------------- | ------------------------- | -------------------------------------------------------------- |
| `~/.bashrc`                         | every interactive bash    | aliases, `PATH`, `EDITOR`, prompt                              |
| `~/.profile` (or `~/.bash_profile`) | login shells (SSH logins) | things for the whole session; on Ubuntu it sources `~/.bashrc` |
| `/etc/profile`, `/etc/bash.bashrc`  | everyone                  | system-wide defaults (admins only)                             |

```sh
$ echo 'alias ll="ls -lah"' >> ~/.bashrc
$ source ~/.bashrc           # reload now, without opening a new terminal
```

### History

`history` lists what you ran. **Ctrl+R** searches it as you type (press it again for older
matches). `!!` repeats the last command, so `sudo !!` re-runs it with sudo.

## Three streams in, three streams out

Every process starts with three standard I/O channels. **Standard input** (file descriptor 0) supplies data;
**standard output** (1) carries normal results; **standard error** (2) carries diagnostics. A terminal is the
default destination for output and the default source for input, but the shell can connect these channels to
files or other programs.

> **Figure.** A process has three streams. stdin, number 0, brings input from the keyboard or a file with less-than. stdout, number 1, is normal output, to the terminal or a file with greater-than. stderr, number 2, is errors, redirected with 2 greater-than. 2 greater-than ampersand 1 sends errors to the same place as output. A pipe connects one command's stdout to the next command's stdin.
>
> Output and errors are separate on purpose: you can save one and still see the other.

That separation is why `ls /etc /nope > out.txt` still shows the error on screen: you redirected
stream 1, and the error travels on stream 2.

Keeping errors separate lets a script save successful output while still showing failures. A pipe connects
one program's standard output to the next program's standard input. Redirect order matters because Bash
processes redirections from left to right. A common mistake is sending only stdout to a log and losing the
error that explains why a scheduled job failed.

## Redirects and pipes

```sh
$ ls /etc > files.txt             # stdout to a file (overwrites it)
$ ls /etc >> files.txt            # append instead
$ ls /etc /nope 2> errors.txt     # only errors to a file
$ ls /etc /nope > all.txt 2>&1    # both, to the same file (order matters)
$ ls /etc /nope &> all.txt        # bash shorthand for the same
$ find / -name "*.conf" 2> /dev/null   # throw errors away
$ sort < names.txt                # stdin from a file
$ ps aux | grep nginx             # pipe: output of one becomes input of the next
$ ./deploy.sh | tee deploy.log    # see output AND save it
$ find . -name "*.log" | xargs gzip    # turn lines of input into arguments
```

> **Figure.** Animated, three runs of ls /etc /nope. With no redirect, normal output (stdout) and the error (stderr) both reach the terminal. With > out.txt, only stdout goes to the file and the error still shows on screen. With > all.txt 2>&1, stderr follows stdout into the file and the screen stays empty.
>
> Green is stdout, red is stderr. Each redirect changes where one of them lands.

`2>&1` reads as "send stream 2 wherever stream 1 is going **right now**". So the file redirect
has to come first. `/dev/null` is a bin that throws away whatever you write to it.

> **In production.** Cron jobs and scripts run with nobody watching. Always capture both streams and append: `./backup.sh >> /var/log/backup.log 2>&1`. Without `2>&1`, the error that explains a failed backup goes nowhere, and you find out the night you need the backup.

> **Video.** [Linux Sysadmin Basics 04 -- Shell Features -- Pipes and Redirection](https://www.youtube.com/watch?v=-Z5tCri-QlI) (tutoriaLinux)

## sudo and root

**root** (user id 0) can do anything: read every file, kill any process, delete the system.
Your normal account can't, and that's protection, not a limitation.

Some maintenance commands need permissions that a normal account should not have all the time. `sudo` runs a
single command with an approved elevated identity and records the request. A root shell is broader: every
command in it can change the whole system, so leave it as soon as the task is complete.

```sh
$ whoami
rajeev
$ sudo systemctl restart nginx    # one command as root; asks YOUR password
$ sudo -l                         # what am I allowed to run with sudo?
$ sudo -i                         # a root shell. The prompt ends in #. Leave with exit
$ sudo !!                         # re-run the last command with sudo
```

|           | `sudo command`           | `su -`               |
| --------- | ------------------------ | -------------------- |
| Asks for  | your password            | root's password      |
| Scope     | one command              | a whole root shell   |
| Logged as | your name, every command | "root", nothing more |

Prefer `sudo` for each command over a long-lived root shell. If you do open one with `sudo -i`,
do the one task and `exit`.

> **sudo doesn't apply to redirects.** `sudo echo "x" > /etc/app.conf` fails with Permission denied: the `>` runs in your shell before sudo starts. Use `echo "x" | sudo tee /etc/app.conf > /dev/null`.

## Mission: Install a tool for yourself, and log it

You keep running the same health-check commands. Turn them into a script called hello that runs from any folder, without sudo, and keeps a log of every run with output and errors.

- You need: A script in ~/bin, and ~/.bashrc
- You'll have: ~/bin/hello and ~/hello.log

```sh
$ mkdir -p ~/bin
$ cat > ~/bin/hello <<'EOF'
#!/bin/bash
echo "$(date '+%F %T') host=$(hostname) user=$USER"
ls /nope                     # a deliberate error, to prove errors are logged too
EOF
$ chmod +x ~/bin/hello
$ echo 'export PATH="$HOME/bin:$PATH"' >> ~/.bashrc
$ source ~/.bashrc
$ type hello
hello is /home/rajeev/bin/hello
$ cd /tmp && hello >> ~/hello.log 2>&1
$ cat ~/hello.log
2026-10-13 10:42:07 host=web-01 user=rajeev
ls: cannot access '/nope': No such file or directory
```

Putting `~/bin` **first** in `PATH` means your tools win over system ones with the same name. Use
that knowingly: never name a script `ls` or `test`.

## Try it

- Run `type ls cd grep` and explain why one of them is a builtin.
- Run `echo $PATH | tr ':' '\n'` and find which directory `grep` lives in with `which grep`.
- Set `GREETING=hi`, check that `bash -c 'echo $GREETING'` prints nothing, then `export` it and run it again.
- Run `ls /etc /nope > out.txt 2> err.txt` and read both files.
- Run `sudo -l` to see what you're allowed to do as root.
- Do the mini mission and check `type hello` reports `~/bin/hello`.

## Quiz

1. You wrote a script `deploy.sh` in your current folder. Typing `deploy.sh` says "command not found". Why?
   - The script is broken
   - **The current folder is not in $PATH, so the shell never looks there; run it as ./deploy.sh** (answer)
   - You need sudo
   Why: The shell only searches the folders listed in $PATH, in order. The current folder is deliberately not one of them (so a file called ls in a random folder can't hijack your ls). ./ gives the path explicitly.

2. You set `API_URL=https://x.test` in your shell, but the script you run next doesn't see it. What's missing?
   - **export API_URL** (answer)
   - sudo
   - A restart
   Why: A plain assignment creates a shell variable, visible only to this shell. export makes it an environment variable, which child processes (your script) inherit.

3. Your cron job should keep a history of every run, output and errors together. Which line is right?
   - ./backup.sh > backup.log
   - **./backup.sh >> backup.log 2>&1** (answer)
   - ./backup.sh 2>&1 >> backup.log
   Why: >> appends instead of overwriting. 2>&1 must come after the file redirect: it means "send errors wherever output is going now". Written first, errors still go to the terminal.

4. Which file should hold `export PATH="$HOME/bin:$PATH"` so it applies to every new terminal on Ubuntu?
   - **~/.bashrc** (answer)
   - /etc/passwd
   - ~/.bash_history
   Why: ~/.bashrc runs for every interactive bash. Login shells read ~/.profile (which on Ubuntu sources ~/.bashrc). /etc/passwd stores accounts, not settings.

5. Why is working as root all day a bad idea, even on your own server?
   - Root is slower
   - **Every typo runs with full power: rm -rf in the wrong folder, a bad chmod, and nothing stops you** (answer)
   - Root cannot use sudo
   Why: sudo is a seat belt: you choose the moments that need power, it asks for confirmation, and every use is logged with your name.

## Resources

- [bash(1) manual page](https://manpages.ubuntu.com/manpages/noble/man1/bash.1.html) (Ubuntu manpages)
- [sudo and sudoedit manual](https://manpages.ubuntu.com/manpages/noble/man8/sudo.8.html) (Ubuntu manpages)
- [LPIC-1 exam 101, objectives 103.1 and 103.4](https://www.lpi.org/our-certifications/exam-101-objectives/) (Linux Professional Institute)
- [explainshell, paste a command and see every part explained](https://explainshell.com/) (explainshell)
