# Work on the command line

> Bash basics for LPIC-1: running and chaining commands, quoting, variables and export, PATH, type and which, man, uname and history.

Source: https://aminbytes.dev/bytes/gnu-and-unix-commands/command-line/


Almost everything in LPIC-1 happens in a terminal. Installing packages, reading logs, managing users, fixing a broken boot: you type it all into a **shell**, the program that reads your commands and runs them. On Linux that shell is almost always **Bash**.

This byte covers the shell skills every other topic builds on: running commands, quoting, variables, how the shell finds programs, reading manuals, and reusing your command history. It's one of the heavier objectives on exam 101, so it pays to know the details.

## The shell and the prompt

Open a terminal and you see a prompt. It usually ends in `$` for a normal user and `#` for root:

```console
amin@web01:~$
root@web01:~#
```

The prompt shows the user, the host name and the current directory (`~` means your home directory). You type a command, press Enter, and Bash runs it.

Check which shell you're in and which version:

```bash
echo $SHELL
echo $BASH_VERSION
```

```text
/bin/bash
5.2.15(1)-release
```

`$SHELL` is your login shell, set in `/etc/passwd`. You can start a new Bash inside the current one by typing `bash`, and leave it again with `exit`. Each nested shell raises the `SHLVL` variable by one.

## Commands, options and arguments

A command line has three kinds of words: the command, its **options** (usually starting with `-` or `--`) and its **arguments** (what to work on).

```bash
ls -l -a /etc
ls -la /etc            # short options can be combined
ls --all --human-readable /etc
```

Here `ls` is the command, `-l` and `-a` are options, and `/etc` is the argument.

### One-line sequences

You can put several commands on one line. How they are joined decides when the next one runs:

| Operator | Meaning | Example |
| --- | --- | --- |
| `;` | Run the next command no matter what | `cd /tmp; ls` |
| `&&` | Run the next command only if the previous one **succeeded** | `mkdir backup && cp notes.txt backup/` |
| `\|\|` | Run the next command only if the previous one **failed** | `ping -c1 web01 \|\| echo "web01 is down"` |

"Succeeded" means the command's **exit status** was `0`. Anything from 1 to 255 means failure. The shell stores the last exit status in `$?`:

```bash
ls /etc > /dev/null; echo $?
ls /nope; echo $?
```

```text
0
ls: cannot access '/nope': No such file or directory
2
```

You can combine both operators. This prints one message or the other:

```bash
ls /nope && echo "found it" || echo "no such dir"
```

```text
ls: cannot access '/nope': No such file or directory
no such dir
```

A long command can be split over several lines with a backslash `\` at the end of each line. The shell joins them before running.

## Quoting

The shell treats some characters as special: spaces split words, `$` starts a variable, `*` is a wildcard, `;` ends a command. **Quoting** tells the shell to take them literally.

| Quoting | What it does | Example | Output |
| --- | --- | --- | --- |
| `"double"` | Keeps spaces, but still expands `$VAR`, `$(cmd)` and `\` escapes | `echo "Hi $USER"` | `Hi amin` |
| `'single'` | Everything literal, no expansion at all | `echo 'Hi $USER'` | `Hi $USER` |
| `\` (backslash) | Makes the one next character literal | `echo Hi \$USER` | `Hi $USER` |

```bash
NAME=Amin
echo "Hi $NAME"
echo 'Hi $NAME'
echo "She said \"hi\""
echo 'it'\''s'
```

```text
Hi Amin
Hi $NAME
She said "hi"
it's
```

The last one is a classic trick: you can't put a single quote inside single quotes, so you close the quotes, add an escaped `\'` and open them again.

Quoting matters most for file names with spaces. `rm my file.txt` tries to delete two files, `my` and `file.txt`. `rm "my file.txt"` deletes one.

### echo

`echo` prints its arguments, followed by a newline. Two options are worth knowing:

```bash
echo -n "no newline"      # -n: don't add the newline at the end
echo -e "one\ttwo\nthree" # -e: interpret \t (tab) and \n (newline)
```

```text
no newlineone	two
three
```

## Variables

A shell variable is a name with a value. You **define** it with `=` and no spaces around it, and you **reference** it with a `$` in front:

```bash
GREETING="hello world"
echo $GREETING
echo "${GREETING}s and more"
```

```text
hello world
hello worlds and more
```

`GREETING = "hi"` (with spaces) fails: Bash thinks `GREETING` is a command. Use braces `${NAME}` when the name is directly followed by other letters, otherwise `$NAMEs` looks for a variable called `NAMEs`.

### Shell variables vs environment variables

A plain assignment creates a **shell variable**. Only the current shell sees it. To pass it to programs you start from this shell (child processes), you **export** it. It then becomes an **environment variable**:

```bash
GREETING="hello world"
bash -c 'echo "child sees: [$GREETING]"'
export GREETING
bash -c 'echo "child sees: [$GREETING]"'
```

```text
child sees: []
child sees: [hello world]
```

You can also define and export in one go: `export EDITOR=vim`. Exports only go *down* to children, never back up to the parent shell, and they're gone when the shell exits. To make them permanent you put them in a startup file like `~/.bashrc` (that's objective 105.1).

### env, set and unset

| Command | What it does |
| --- | --- |
| `env` | Lists **environment** (exported) variables only |
| `set` | Lists **all** shell variables, environment variables and functions |
| `export` | Marks a variable for export; `export -p` lists exported ones |
| `unset NAME` | Deletes a variable (no `$` in front of the name) |
| `env VAR=value cmd` | Runs one command with a changed environment |
| `env -i cmd` | Runs a command with an empty environment |

```bash
env | head -3
unset GREETING
echo "after unset: [$GREETING]"
```

```text
HOSTNAME=web01
PWD=/home/amin
HOME=/home/amin
after unset: []
```

You can also set a variable for a single command without `env`, by putting the assignment in front of it:

```bash
TZ=UTC date
LANG=C ls --help
```

`set` has a second job: switching shell options on and off. `set -o` lists them, `set -o noclobber` turns one on and `set +o noclobber` turns it off again. `set -x` prints each command before running it, which is handy for debugging.

### Variables you'll meet everywhere

| Variable | Holds |
| --- | --- |
| `HOME` | Your home directory |
| `USER` | Your user name |
| `PATH` | Directories searched for commands |
| `PWD` / `OLDPWD` | Current and previous directory |
| `SHELL` | Your login shell |
| `PS1` | The look of your prompt |
| `HISTFILE`, `HISTSIZE` | Where history is saved, how much is kept |
| `EDITOR` | Your preferred text editor |
| `$?`, `$$`, `$!` | Last exit status, PID of this shell, PID of the last background job |

## How the shell finds commands: PATH

When you type `ls`, Bash has to find a program called `ls`. It checks in this order: aliases, keywords (like `if`), functions, builtins (commands built into Bash itself, like `cd`), and finally the directories listed in `PATH`, left to right.

```bash
echo $PATH
```

```text
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
```

The first match wins. If nothing matches, you get `command not found` and exit status `127`.

### type and which

`type` is a Bash builtin, so it knows everything Bash knows. `which` is a separate program that only searches `PATH`:

```bash
type uname cd type
type -a echo
which uname bash
which cd; echo $?
```

```text
uname is /usr/bin/uname
cd is a shell builtin
type is a shell builtin
echo is a shell builtin
echo is /usr/bin/echo
echo is /bin/echo
/usr/bin/uname
/usr/bin/bash
1
```

`type -a` shows every match, in the order Bash would try them. That's how you spot that `echo` exists as a builtin *and* as a program. Aliases show up too. Many distributions alias `ls` for colors, so in an interactive shell you may see:

```console
$ type ls
ls is aliased to `ls --color=auto'
$ alias ll='ls -l'
$ type ll
ll is aliased to `ls -l'
```

`which cd` finds nothing, because `cd` isn't a file. It has to be a builtin: a separate program can't change the directory of your shell.

### Running commands outside the PATH

The current directory is **not** in `PATH` on purpose. Otherwise a malicious file called `ls` in some folder could run when you type `ls` there. So to run a script in the current directory, give a path to it:

```bash
hello.sh            # bash: hello.sh: command not found
./hello.sh          # relative path: run it from here
/home/amin/hello.sh # absolute path
bash hello.sh       # or hand the file to bash
```

Any command with a `/` in it skips the `PATH` search. Common places to put your own scripts so they *are* in `PATH`: `~/bin` or `~/.local/bin` (Debian and Ubuntu add them automatically from `~/.profile` when they exist), or `/usr/local/bin` for all users. To add a directory yourself:

```bash
export PATH="$PATH:$HOME/scripts"
```

 (Side note: Bash remembers where it found each command in a small table, so it doesn't search `PATH` every time. If you move a program and Bash keeps looking in the old place, run `hash -r` to clear that table.)

## Where you are and what you're on: pwd and uname

`pwd` (print working directory) shows the current directory. `pwd -P` resolves symbolic links and shows the physical path.

```bash
pwd
cd /tmp
cd -        # back to the previous directory ($OLDPWD)
```

`uname` prints information about the kernel and the machine:

| Option | Shows | Example |
| --- | --- | --- |
| (none) or `-s` | Kernel name | `Linux` |
| `-n` | Network host name | `web01` |
| `-r` | Kernel release | `6.1.0-28-amd64` |
| `-v` | Kernel build version and date | `#1 SMP PREEMPT_DYNAMIC Debian 6.1.119-1 (2024-11-22)` |
| `-m` | Machine hardware | `x86_64` |
| `-o` | Operating system | `GNU/Linux` |
| `-a` | All of the above | |

`uname -r` is the one you'll use most, for example to find the matching modules in `/lib/modules/$(uname -r)/`.

## Reading the manual: man

Every command, config file and system call has a manual page. `man` opens it in a pager:

```bash
man ls
man 5 passwd     # the file format of /etc/passwd
man 7 regex      # regular expressions overview
```

Man pages are split into numbered **sections**. The same name can live in several of them: `passwd(1)` is the command, `passwd(5)` is the file.

| Section | Contents |
| --- | --- |
| 1 | User commands (`ls`, `grep`) |
| 2 | System calls (`open`, `fork`) |
| 3 | Library functions (`printf` in C) |
| 4 | Special files in `/dev` |
| 5 | File formats and config files (`passwd`, `fstab`) |
| 6 | Games |
| 7 | Miscellaneous: overviews and conventions (`regex`, `signal`) |
| 8 | System administration commands, usually for root (`mount`, `useradd`) |

Without a section number, `man` shows the first match in the order it searches. `man -a passwd` shows them all, one after the other.

Inside `man`, the keys are the ones of `less`: `Space` for the next page, `b` to go back, `/word` to search forward, `n` for the next hit, `q` to quit, `h` for help.

When you don't know the command name, search the short descriptions:

```bash
man -k partition     # same as: apropos partition
man -f passwd        # same as: whatis passwd
```

```text
passwd (1)           - change user password
passwd (5)           - the password file
```

`man -k` uses a database built by `mandb`. If it says "nothing appropriate", run `sudo mandb` once. Man pages live under `/usr/share/man/`. Many commands also print a short summary with `--help`.

> [!TIP]
> Minimal container images (`debian`, `ubuntu`) leave out man pages to save space. Practice `man` on a VM or a normal install, or install `man-db` and run `unminimize` on Ubuntu.

## Command history

Bash remembers what you type. Press the Up and Down arrows to walk through earlier commands, or list them:

```bash
history 5
```

```text
  101  cd /etc
  102  grep root passwd
  103  ls -l /var/log
  104  sudo systemctl status ssh
  105  history 5
```

### Reusing old commands

| Typed | Runs |
| --- | --- |
| `!!` | The previous command (`sudo !!` reruns it with sudo) |
| `!103` | Command number 103 from the list |
| `!-2` | The command two back |
| `!grep` | The most recent command that **starts** with `grep` |
| `!?passwd` | The most recent command that **contains** `passwd` |
| `!$` | The last argument of the previous command |
| `^old^new` | The previous command with `old` replaced by `new` |
| `Ctrl+R` | Reverse search: type a part, press `Ctrl+R` again for older matches |

```console
$ mkdir /tmp/project
$ cd !$
cd /tmp/project
```

Bash prints the expanded command before running it, so you can see what happened.

### Where history is stored

While the shell runs, history lives in memory. When the shell exits, it's written to the file in `HISTFILE`, by default `~/.bash_history`. Two variables control the size:

- `HISTSIZE`: how many commands are kept in memory (Bash's own default is 500; Debian and Ubuntu set 1000 in `~/.bashrc`, RHEL and Fedora set 1000 in `/etc/profile`).
- `HISTFILESIZE`: how many lines are kept in the file (Debian's `~/.bashrc` sets 2000).

`HISTCONTROL` decides what's left out. `ignorespace` skips commands that start with a space (handy for a command with a password in it), `ignoredups` skips repeats, and `ignoreboth` does both (the Debian default).

```bash
history -c       # clear the history in memory
history -d 102   # delete one entry
history -w       # write memory to ~/.bash_history now
history -a       # append this session's new lines to the file now
```

 (Side note: Each terminal keeps its own history in memory and writes it at exit, so the last shell to close can overwrite what the others saved. Adding `shopt -s histappend` to `~/.bashrc` (Debian and Ubuntu already do) makes Bash append instead.)

### Editing the command line

Bash's line editor has shortcuts that save a lot of arrow-key presses:

| Keys | Action |
| --- | --- |
| `Tab` | Complete a command or file name (twice: show all options) |
| `Ctrl+A` / `Ctrl+E` | Jump to the start / end of the line |
| `Ctrl+U` / `Ctrl+K` | Cut from the cursor to the start / end of the line |
| `Ctrl+W` | Cut the word before the cursor |
| `Ctrl+L` | Clear the screen |
| `Ctrl+C` | Abandon the current line (or stop the running command) |

## Exam checklist

- A command's exit status is in `$?`: `0` is success. `&&` runs on success, `||` on failure, `;` always.
- Double quotes expand `$VAR` and `$(...)`; single quotes expand nothing; `\` escapes one character.
- `VAR=value` (no spaces) makes a shell variable. `export VAR` makes it visible to child processes. `unset VAR` removes it.
- `env` lists environment variables only; `set` lists all variables and functions, and also sets shell options (`set -o noclobber`).
- `type` knows builtins, aliases, functions and keywords; `which` only searches `PATH`. `type -a` shows every match.
- The current directory isn't in `PATH`: run local scripts with `./script.sh` or a full path. Not found means exit status `127`.
- `uname -r` = kernel release, `uname -a` = everything, `uname -m` = hardware, `uname -n` = host name.
- Man sections: 1 user commands, 5 file formats, 7 overviews (`regex(7)`), 8 admin commands. `man -k` = `apropos`, `man -f` = `whatis`.
- History is saved to `~/.bash_history` (`HISTFILE`) on exit. `!!`, `!n`, `!string`, `!$` and `Ctrl+R` reuse commands. `HISTSIZE` is for memory, `HISTFILESIZE` for the file.


## Byte check

1. You run `NAME=Amin` and then `bash -c 'echo $NAME'`. It prints an empty line. What fixes it?
   - **`export NAME`** (correct)
   - `set NAME`
   - `env NAME`
   A plain assignment makes a shell variable that only the current shell sees. `export` turns it into an environment variable, which child processes like the new `bash` inherit.

2. Which command tells you that `cd` is a shell builtin, not a program on disk?
   - `which cd`
   - **`type cd`** (correct)
   - `whereis cd`
   `type` is a builtin itself, so it knows about builtins, aliases, functions and keywords. `which` only searches the directories in `PATH` and finds nothing for `cd`.

3. What does `echo 'Cost: $HOME'` print?
   - `Cost: /home/amin`
   - **`Cost: $HOME`** (correct)
   - `Cost: `
   Single quotes turn off every special character, so `$HOME` is printed literally. Double quotes would expand it.


