# User Environment Variables

**Environment variables** are dynamic values that play a crucial role in defining the behavior and configuration of processes and applications within an operating system. They act as key-value pairs, where each variable holds specific information that can be accessed by programs, scripts, or the system itself. These variables can store a wide range of data, such as file paths, user preferences, system settings, or even sensitive information like API keys and passwords.

Some common examples include:

* **`PATH`**: Specifies directories where executable programs are located.
* **`HOME`**: Points to the current user’s home directory.
* **`USER`**: Stores the username of the current user.

**Environment variables are used in Linux to configure and customize the behavior of the system, applications, and processes.** They store key-value pairs that define settings like file paths, user preferences, and system configurations, enabling programs to adapt to different environments dynamically. For example, the `PATH` variable tells the system where to find executable programs, while `HOME` points to the user’s home directory. Environment variables also enhance security by storing sensitive data like API keys or passwords outside of code, reducing the risk of exposure. They simplify scripting by allowing scripts to access shared data, and they ensure cross-platform compatibility by providing a consistent way to manage configurations across different systems. Overall, environment variables make Linux systems more flexible, secure, and user-friendly.

## Viewing and Modifying Environment Variables

To list all environment variables, use the `printenv` or `env` command:

```jsx
┌──(kali㉿kali)-[~/Desktop]
└─$ env
SHELL=/usr/bin/bash
SESSION_MANAGER=local/kali:@/tmp/.ICE-unix/913,unix/kali:/tmp/.ICE-unix/913
WINDOWID=0
QT_ACCESSIBILITY=1
COLORTERM=truecolor
XDG_CONFIG_DIRS=/etc/xdg
XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0
XDG_MENU_PREFIX=xfce-
POWERSHELL_UPDATECHECK=Off
---snip---

┌──(kali㉿kali)-[~/Desktop]
└─$ printenv

SHELL=/usr/bin/bash
SESSION_MANAGER=local/kali:@/tmp/.ICE-unix/913,unix/kali:/tmp/.ICE-unix/913
WINDOWID=0
---snip---
```

Environment variables are always uppercase, as in `HOME, PATH, SHELL`, and so on. These are only the default environment variables that come on your system. A user can also create their own variables, and as you will see, we need a different command to include those in the output.

## Filtering for Particular Variables

Although using `set` with `more` provides more manageable results than sifting through the extensive list of variable names generated by `set` alone, it can still be quite time-consuming if you're searching for a specific variable. A more efficient approach is to use the filtering command `grep` to pinpoint the variable you're interested in.

Let’s consider the variable `PATH` as an example. This variable contains a list of directories that your shell searches through when you execute a command. These directories are checked in the order they appear in the `PATH` variable, and the first matching executable found is the one that runs. Note that `PATH` doesn’t store the actual commands, but rather the locations where the system looks for them.

To find the `PATH` variable, you can pipe the output of `set` to `grep` like this:

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ set | grep PATH
BASH_LOADABLES_PATH=/usr/local/lib/bash:/usr/lib/bash:/opt/local/lib/bash:/usr/pkg/lib/bash:/opt/pkg/lib/bash:.
PATH=/home/kali/.local/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/home/kali/.dotnet/tools
XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat0
XDG_SESSION_PATH=/org/freedesktop/DisplayManager/Session0
    local PATH=$PATH:/sbin;
    _comp_compgen -c    
---snip---
```

This will filter the output of `set` to display only the lines containing the `PATH` variable, making it easier to locate and inspect.

## Changing Variable Values for a Session

In a shell session, you can modify the values of environment variables to customize your environment or control specific behaviors. Let’s explore how to change a variable’s value using the `PS1` variable as an example. This variable defines the appearance of your shell prompt. By default, it displays basic information like the username, hostname, and current directory, but you can customize it to include additional details or change its format.

For instance, if you want to simplify your prompt to show only the current directory, you can modify the `PS1` variable as follows:

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ PS1="\w\$ "                                                    

~/Desktop$ ls
```

After making this change, your prompt will display only the current working directory followed by a $ symbol.

## **Understanding and Modifying Your `PATH` Variable**

One of the most critical environment variables in your system is the `PATH` variable. It determines where your shell looks for executable commands when you type them in the terminal. For example, when you enter commands like `cd`, `ls`, or `echo`, the shell searches through the directories listed in the `PATH` variable to find and execute those commands. Most system commands are located in directories such as `/usr/local/sbin`, `/usr/local/bin`, `/usr/sbin`, and `/bin`. If the shell can’t find a command in any of the directories listed in `PATH`, it will return an error like `command not found`, even if the command exists in a directory not included in `PATH`.

To view the directories currently in your `PATH` variable, you can use the `echo` command:

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ echo $PATH
/home/kali/.local/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/home/kali/.dotnet/tools
```

These are the directories where your terminal searches for commands. For instance, when you type `ls`, the system checks each of these directories in order, finds the `ls` executable, and runs it. Each directory in the `PATH` is separated by a colon (`:`).

#### Adding a Directory to Your `PATH` Variable

Understanding your `PATH` is important because it affects how you use tools and commands. For example, if you install a new tool, say `newhackingtool`, in a directory like `/root/newhackingtool`, you won’t be able to run commands from this tool unless you’re in that directory. This can be inconvenient if you need to use the tool frequently.

To make the tool accessible from any directory, you need to add its directory to your `PATH` variable. Here’s how you can do it:

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$ PATH=$PATH:/root/ncateam
```

This command appends `/root/ncateam` to the existing `PATH` variable. Now, when you check the `PATH` again, you’ll see the new directory added:

```jsx
┌──(kali㉿kali)-[~/Desktop]
└─$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/root/ncateam
```

With this change, you can run commands from `newhackingtool` from any directory, as the shell will now search `/root/ncateam` for executables.

## A Common Mistake: Overwriting the `PATH` Variable

A common mistake beginners make is overwriting the `PATH` variable instead of appending to it. For example, if you run:

```bash
┌──(kali㉿kali)-[~/Desktop]
└─$  PATH=/root/ncateam
```

Your `PATH` will now **only** include `/root/ncateam`, and none of the default system directories like `/bin`, `/sbin`, or `/usr/bin`. This means essential system commands like `cd`, `ls`, or `echo` will no longer work, and you’ll see errors like:

## Creating a User-Defined Variable

In the shell, you can create your own custom variables, known as user-defined variables, to store data, simplify tasks, or customize your environment. These variables are particularly useful for avoiding repetitive typing and making your workflow more efficient. To create a user-defined variable, you simply assign a value to a name of your choice. For example, if you frequently work with a directory like `/root/my_tools`, you can create a variable called `MY_TOOL_DIR` and assign the directory path to it: `MY_TOOL_DIR="/root/my_tools"`. Once defined, you can access the value of the variable using the `$` symbol, such as `echo $MY_TOOL_DIR`, which will output `/root/my_tools`.

User-defined variables can be used in place of hardcoded values in commands. For instance, instead of typing `cd /root/my_tools` every time you want to navigate to that directory, you can simply use `cd $MY_TOOL_DIR`. This not only saves time but also reduces the chance of errors. If you want the variable to be available in child processes or scripts, you can export it using the `export` command, like `export MY_TOOL_DIR`. However, by default, user-defined variables are temporary and only exist for the current shell session. To make them persistent across sessions, you can add the variable definition to your shell’s configuration file, such as `.bashrc` or `.zshrc`. For example, adding `export MY_TOOL_DIR="/root/my_tools"` to `.bashrc` ensures the variable is available every time you open a new terminal.

A practical use case for user-defined variables is simplifying access to frequently used scripts or tools. For example, if you have a script located at `/root/scripts/myscript.sh`, you can create a variable like `MY_SCRIPT="/root/scripts/myscript.sh"` and run the script with `bash $MY_SCRIPT`. This approach eliminates the need to remember or type long paths repeatedly. By leveraging user-defined variables, you can make your shell environment more efficient, organized, and tailored to your specific needs.

```bash
┌──(kali㉿kali)-[~/Desktop]                                                                                                            
└─$ message='hello world'                                                                                                            
                                                                                                                                       
┌──(kali㉿kali)-[~/Desktop]                                                                                                            
└─$ echo $message                                                                                                                      
hello world           

┌──(kali㉿kali)-[~/Desktop]                                                                                                            
└─$ unset message

┌──(kali㉿kali)-[~/Desktop]
└─$ echo $message
```

`unset` command in the shell is used to **remove or delete a variable** (or a function) from the environment.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://handbook.ncateam.xyz/fundamentals/linux/user-environment-variables.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
