Shell Scripting: Variables and Environment Variables

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Shell Variables

You can set variables using the = operator (no spaces around =):

name=value
ROOM_NUMBER=237
name=Flavio
nickname="Flavio"

Print a variable by prepending $:

echo $ROOM_NUMBER
echo $name

Strings

Always use quotes around strings when working with them:

dogname="Roger"

Get string length with ${#variable}:

echo ${#dogname}  # outputs: 5

Compare strings:

"$dogname" == "$anotherdogname"
"$dogname" != "$anotherdogname"

Environment Variables

Environment variables are values you can set outside of programs to alter their execution. An API key or configuration value, for example.

Set an environment variable:

export VARIABLE=something

With spaces, use quotes:

export VARIABLE="variable value"

This works the same in Bash and Zsh. To persist them:

  • Bash: add to .bashrc or .bash_profile
  • Zsh: add to .zshrc

After editing a dot file, apply changes with:

source ~/.bashrc

System Environment Variables

The system sets up some environment variables for you:

  • $HOME - your home folder
  • $LOGNAME - your user name
  • $SHELL - the path to your default shell
  • $PATH - where the shell looks for commands
  • $PWD - current working directory

Inspect their values:

echo $HOME     # /Users/flavio
echo $LOGNAME  # flavio
echo $SHELL    # /bin/bash

The $PATH Variable

$PATH is a list of folders where the shell looks for commands, separated by colons:

echo $PATH
# /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

Add a folder to your path in .bashrc or .zshrc:

export PATH="$PATH:/Users/flavio/bin"

Operators

Bash implements arithmetic operators:

  • + add
  • - subtract
  • * multiply
  • / divide
  • % modulo
  • ** exponentiation

Comparison operators for numbers:

  • -lt lower than
  • -gt greater than
  • -le lower or equal
  • -ge greater or equal
  • -eq equal to
  • -ne not equal to

Logical operators:

  • && logical AND
  • || logical OR

Lessons in this unit:

0: Introduction
1: Introduction to Shells
2: Bash Basics
3: Writing Shell Scripts
4: ▶︎ Variables and Environment Variables
5: Loops and Arrays
6: Shell Script Functions
7: Creating Aliases
8: Tips and Tricks
9: The Fish Shell
10: Persist aliases and other configuration in Fish Shell
11: How to add a path to Fish Shell
12: Fish Shell, how to avoid recording commands to history
13: Fish Shell, how to remove the welcome message
14: How to replace all filenames with space with underscore using a shell script
15: How to update all npm packages in multiple projects that sit in subfolders