CIS120 Linux Fundamentals by Scott Shaper

Linux Environment

Think of the Linux environment like a personalized workspace that remembers your preferences. Just like how you might arrange your desk with specific tools and decorations, the Linux environment stores information about your system setup, favorite shortcuts, and personal settings. Understanding how to work with this environment helps you customize your Linux experience to work exactly the way you want it to.

Quick Reference

Command What It Does Common Use
printenv Display environment variables Checking system configuration values
set Display/set shell options and variables Viewing all variables, changing shell behavior
export Make variables available to child processes Setting environment variables permanently
alias Create command shortcuts Creating custom commands and shortcuts

When to Use Environment Commands

Understanding Environment Types

Think of the Linux environment like layers of settings that affect how your system works:

Type What It Contains Real-World Example
Environment Variables System-wide settings shared with programs Like the building rules everyone follows
Shell Variables Settings specific to your current shell Like your personal desk arrangement
Aliases Custom command shortcuts Like speed-dial numbers on your phone
Shell Functions Mini-programs for your terminal Like custom tools you've built for yourself

The printenv Command

Think of printenv like a window into your system's configuration. It lets you see the environment variables that control how programs behave. Environment variables are like system-wide settings that programs can access to understand their operating context.

When you run printenv without any arguments, it displays all environment variables currently defined in your session. These variables contain information about your user account, system configuration, and program settings. Each line shows a variable name followed by an equals sign and its value.

Environment variables are used by many programs to determine how they should behave. For example, your terminal program uses the TERM variable to know what features your terminal supports, while commands like less and more use the PAGER variable to control their behavior.

Option What It Does When to Use
No options Shows all environment variables When you want to see everything
Variable name Shows value of specific variable When you need one particular setting

Practical Examples

# See all environment variables
printenv | less

# Check a specific variable
printenv USER

# Check your home directory path
printenv HOME

# See where programs are found
printenv PATH

# Check multiple variables at once
printenv USER HOME SHELL

# Check if a variable exists (returns nothing if it doesn't exist)
printenv NONEXISTENT_VARIABLE

Unlike the set command, printenv only shows environment variables (not shell variables). This makes it useful when you're specifically interested in variables that are passed to programs you run, rather than variables that only affect your current shell.

The set Command

Think of set as your control panel for the shell. It shows all variables (both environment and shell) and lets you change how your shell behaves. The set command is more comprehensive than printenv because it displays both environment variables and shell variables, along with any defined functions.

Shell variables are used only by the shell itself and aren't passed to programs you run. They control how the shell behaves, store temporary values for scripts, and hold special information about your shell session. Environment variables, on the other hand, are passed to child processes (programs you run).

The set command without options displays all variables in alphabetical order, making it easier to find specific variables. It also shows function definitions, which are mini-programs you can define in your shell.

Beyond viewing variables, set can change fundamental behaviors of your shell through shell options. These options can make your shell stricter or more verbose, which is particularly useful when debugging scripts.

Option What It Does When to Use
No options Shows all variables and functions When you want to see everything
-o Sets a shell option When changing shell behavior
+o Unsets a shell option When reverting shell behavior
-u Treats unset variables as errors When writing robust scripts
-x Prints commands as they execute When debugging scripts
-e Exits if a command fails When you want scripts to stop on errors
-v Prints input lines as they are read When debugging complex scripts

Practical Examples

# See all variables and functions
set | less

# Create a shell variable (not an environment variable)
MY_VAR="Hello World"
echo $MY_VAR

# Enable error on unset variables
set -u
echo $UNDEFINED_VARIABLE  # This will now cause an error

# Show commands as they execute (debugging)
set -x
ls -l
cd /tmp
set +x  # Turn off command printing

# Make scripts exit on first error
set -e

# See current shell options
set -o

# Turn on multiple options at once
set -eux

The set command is particularly valuable for script writers, as it provides options that can help catch errors early and make debugging easier. For everyday use, it's mainly used to view all variables or to see the current shell options.

The export Command

Think of export like sharing your settings with others. It makes variables available to any programs that your shell starts. In technical terms, it marks a variable for export to the environment of child processes (programs you run from your shell).

By default, variables you create in your shell (like X=123) are only available in that shell session. They're called "shell variables" and aren't passed to programs you run. When you use export, you're telling the shell "this variable should be shared with any programs I run from here."

For example, if you set EDITOR=vim but don't export it, programs that check the EDITOR variable won't see your preference. But if you use export EDITOR=vim, any program that looks for an editor preference will know to use vim.

The export command can be used in three main ways: to create and export a new variable in one step, to export an existing variable, or to list all currently exported variables.

Syntax What It Does When to Use
export VAR=value Creates and exports variable When setting new environment variables
export VAR Exports existing variable When making shell variable available to programs
export -p Lists all exported variables When checking what's shared with programs
export -n VAR Removes variable from export list When preventing a variable from being shared

Practical Examples

# Set and export a new variable
export EDITOR=vim

# Create a shell variable, then export it later
MY_VAR="Hello World"
export MY_VAR

# Add to PATH (preserving existing path)
export PATH=$PATH:$HOME/bin

# Set multiple variables at once
export VAR1="value1" VAR2="value2"

# List all exported variables
export -p

# Stop exporting a variable (it remains as a shell variable)
export -n SECRET_VAR

# Use exported variables in action
export GREP_COLOR='1;32'
grep --color=auto "pattern" file.txt  # Uses your color preference

The most common use of export is in startup files like .bashrc or .bash_profile, where it sets environment variables that will be available for your entire login session. Variables like PATH, EDITOR, LANG, and PS1 are typically set and exported in these files.

Remember that exported variables are only passed downstream to child processes. Changes you make in a child process (like a script) can't affect the parent shell's environment. For that, you would need to source a script using the source command or the . operator.

The alias Command

Think of alias like creating shortcuts for commands. It's like programming speed-dial numbers for frequently used commands. Aliases allow you to create your own command names that expand to longer or more complex commands, saving you time and typing effort.

An alias is essentially a text substitution. When you type an alias at the command line, the shell substitutes it with its defined value before execution. This allows you to create shorter names for commands you use often, add default options to commands, or create entirely new command names that combine multiple actions.

For example, if you frequently use ls -l to list files with details, you could create an alias ll that automatically expands to ls -l. Similarly, you might create safer versions of commands by adding options like -i (interactive) to rm, which prompts for confirmation before deleting files.

Aliases are just text substitutions, so they have some limitations: they can only be used as the first word on a command line, and they don't accept arguments in the middle of the alias definition. For more complex operations, shell functions (which are more flexible) are needed.

Syntax What It Does When to Use
alias Lists all defined aliases When checking existing shortcuts
alias name='command' Creates a new alias When making a command shortcut
unalias name Removes an alias When deleting a shortcut
unalias -a Removes all aliases When resetting to default commands
alias name Shows definition of specific alias When checking what a shortcut does

Practical Examples

# List all defined aliases
alias

# Create a shortcut for listing files
alias ll='ls -l'

# Create an alias with multiple commands (using semicolons)
alias update='sudo apt update; sudo apt upgrade'

# Create a safer remove command
alias rm='rm -i'

# Show what a specific alias does
alias ll

# Create an alias that includes options and arguments
alias grep='grep --color=auto'

# Create a completely new command name
alias showspace='du -sh * | sort -h'

# Remove an alias
unalias ll

# Remove all aliases
unalias -a

Aliases defined at the command line only last for your current session. To make them permanent, add them to your shell's startup files, typically ~/.bashrc. Most Linux distributions come with some default aliases already set up.

One caution with aliases: they can hide the original commands, which might be confusing to others using your account. You can always bypass an alias by using the full path to the command (like /bin/rm instead of rm) or by preceding the command with a backslash (like \rm).

Important Environment Variables

Think of these variables like the key settings that control your Linux experience:

Variable What It Stores Why It's Important
HOME Your home directory path Used by programs to find your personal files
PATH Where programs are found Determines which commands are available
USER Your username Identifies who you are to programs
SHELL Your default shell Determines your command interpreter
PS1 Your command prompt appearance Controls how your prompt looks
EDITOR Your preferred text editor Used by programs that need to edit text
LANG Your language preferences Controls language and text formatting

Startup Files

Think of startup files like instruction manuals that are read when you log in. They set up your environment according to your preferences.

File When It's Read Common Use
/etc/profile During login (all users) System-wide settings
~/.bash_profile During login (your user) User-specific login settings
~/.bashrc For every new terminal Your shell customizations
~/.profile During login (alternative) User-specific login settings

Example .bashrc File

# Set some useful aliases
alias ll='ls -l'
alias la='ls -a'
alias rm='rm -i'

# Set custom prompt
PS1='\u@\h:\w\$ '

# Add personal bin directory to PATH
PATH=$PATH:$HOME/bin

# Set preferred editor
export EDITOR=vim

# Add custom function
weather() {
    curl wttr.in/$1
}

Tips for Success

Common Mistakes to Avoid

Best Practices

Practical Environment Customizations

Common Customization Examples

# Create a more informative prompt
export PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

# Add color to ls command
export LS_COLORS='di=1;34:fi=0:ln=1;36:pi=5:so=5:bd=5:cd=5:or=31:mi=0:ex=1;32'
alias ls='ls --color=auto'

# Set up better command history
export HISTSIZE=10000
export HISTFILESIZE=10000
export HISTCONTROL=ignoreboth:erasedups

# Create useful shortcut commands
alias update='sudo apt update && sudo apt upgrade'
alias cls='clear'
alias ..='cd ..'
alias ...='cd ../..
'