CertNote/ Commute Study Notes
Roadmap
KOEN
CLF-C02 · FoundationalCloud Practitioner - Foundational
DVA-C02 · AssociateDeveloper - Associate
SAA-C03 · AssociateSolutions Architect - Associate
SOA-C02 · AssociateCloudOps Engineer - Associate
SAP-C02 · ProfessionalSolutions Architect - Professional
DOP-C02 · ProfessionalDevOps Engineer - Professional
Linux Master 2 · 2급KAIT Linux Master - Level 2
  • Week 1
    • 1.Operating Systems and the Kernel: What Linux Does
    • 2.The Birth of Linux: From Unix to Linus
    • 3.Free Software and Open Source: What a License Decides
    • 4.Distributions: The Unit That Bundles the Kernel and Tools for Sale
    • 5.Week 1 Review: The Identity Behind the Name Linux
  • Week 2
  • Week 3
  • Week 4
  • Week 5
    • 1.What Is a Shell?
    • 2.Shell Variables and Environment Variables
    • 3.Environment Configuration Files
    • 4.Redirection · Aliases · History
    • 5.Week 5 Comprehensive Review: The Shell on One Page
  • Week 6
  • Week 7
  • Week 8
  • Week 9
  • Week 10
  • Week 11
SCS-C03 · SpecialtySecurity - Specialty
Linux Master 1 · 1급KAIT Linux Master - Level 1
MLA-C01 · AssociateMachine Learning Engineer - Associate
AIF-C01 · FoundationalAI Practitioner - Foundational
DEA-C01 · AssociateData Engineer - Associate
MLS-C01 · SpecialtyMachine Learning - Specialty
SQLD · 개발자SQL Developer (SQLD)

© CertNote · 주간랩스

  • About
  • Changelog
  • Contact
  • Terms
  • Privacy
← Linux Master 2/Week 5/Day 2

Based on the Linux Master 2 exam syllabus·Report an error

Linux Master 2· AssociateWeek 5 · Day 2~5 min read

Day 2 - Shell Variables and Environment Variables

📌 Key Points

  • You create a variable with name=value. There must be no spaces on either side of the equals sign.
  • A shell variable lives only in the current shell, while an environment variable is passed down to child processes. That difference is everything.
  • The command that promotes a shell variable to an environment variable is export.
  • To get a value out, use $name, as in echo $PATH.
  • PATH is the list of paths where commands are searched for, and the separator is the colon (:).

Creating Variables

NAME=linux           # create — no spaces around the equals sign!
echo $NAME           # linux
echo ${NAME}         # wrapping in braces also works
NAME="hello world"   # use quotes when the value contains spaces
unset NAME           # delete

Spaces are an easy source of mistakes. If you write NAME = linux, the shell treats NAME as a command and tries to run it. Write = with no spaces on either side.

  • By convention, variable names use uppercase. It is not required, but it makes them easy to tell apart from system variables.
  • Add $ only when retrieving the value. Do not add it when creating the variable.

Naming Rules and Braces

RuleValid examplesInvalid examples
Use only letters, digits, and underscores (_)MY_NAME, dir2MY-NAME, my.name
Cannot start with a digitv11v
Case-sensitiveName and NAME are different variables—
FILE=report
echo $FILE_backup      # (blank line)        ← looks for a variable named FILE_backup
echo ${FILE}_backup    # report_backup
  • Braces mark where the variable name ends. They are needed when other characters follow immediately.
  • Reading an undefined variable gives an empty value, not an error. A mistyped name passes silently, so typos are hard to notice.

Values That Change Depending on Quotes

NAME=linux
echo "I use $NAME"            # I use linux           double quotes — variable is replaced by its value
echo 'I use $NAME'            # I use $NAME           single quotes — literal text
echo "Today is `date +%F`"    # Today is 2026-10-14   backticks — result of running a command
echo "Today is $(date +%F)"   # same as above
SymbolName$variable inside it
" "Double quotesIs replaced by its value
' 'Single quotesIs not replaced (literal text)
` `BackticksReplaced by the result of running the command inside. Same as $( )
\BackslashRemoves the special meaning of the one character right after it — echo \$NAME prints $NAME

Double quotes let it through; single quotes block it. Both group whitespace into a single value, but they differ in whether $ is interpreted. Backticks look like quotes, but they do something completely different: run a command.

Shell Variables vs Environment Variables

   Current shell
   ├── NAME=linux        (shell variable)        ─┐
   └── export AGE=30     (environment variable)  ─┼─ what gets passed to the child?
        │                                         │
        ▼ run a child process                     │
      Child shell                                 │
        NAME → empty  ◄───────────────────────────┘  not passed
        AGE  → 30                                    passed
CategoryShell variableEnvironment variable
ScopeCurrent shell onlyDown to child processes
CreatingNAME=valueexport NAME=value
Viewingsetenv or printenv
ExamplesVariables a user created temporarilyPATH, HOME, SHELL
NAME=linux              # shell variable
export NAME             # promote to environment variable
export AGE=30           # create and make it an environment variable at once
CommandWhat it shows
setShell variables + environment variables, all of them
envEnvironment variables only
printenvEnvironment variables only (similar to env)
exportThe list of environment variables
unset nameDeletes a variable

set shows everything, env shows only environment variables. This pair is within the exam scope. In terms of output range, set is the wider one.

Check It Yourself: Is It Visible in the Child Shell?

NAME=linux             # shell variable
export AGE=30          # environment variable
bash                   # enter a child shell
echo "[$NAME] [$AGE]"
# [] [30]              ← NAME is empty and only AGE came through
AGE=99                 # try changing the value in the child
exit                   # return to the parent shell
echo $AGE
# 30                   ← the parent's value is unchanged
  • Passing goes one way, parent → child. The child receives a copy of the parent's environment, so whatever the child changes never reaches the parent.
  • A script run with bash script.sh is also a child shell. A variable you export inside a script disappears when the script ends.
  • Once a variable has been exported, it stays an environment variable even if you change its value again. You do not need to export again each time you change it.

More Commands for Working with Variables

export -p | head -3
# declare -x HOME="/home/user"
# declare -x LANG="ko_KR.UTF-8"
# declare -x LOGNAME="user"
printenv HOME          # /home/user        ← giving a name prints only that value
env | grep LANG        # LANG=ko_KR.UTF-8
export -n AGE          # turn an environment variable back into a shell variable (value remains)
unset AGE              # delete the variable itself
env LANG=C date        # run this one command with LANG changed
# Wed Oct 14 09:30:00 KST 2026
Easily confused pairDifference
unset vs export -nDeletes the variable / keeps the value and only removes its environment-variable status
env vs printenvBoth print environment variables. printenv lets you specify a name, and env can run a command in a temporary environment
set vs envThe output of set includes not only shell variables but also shell functions
  • In the declare -x from export -p output, the x is the export attribute. So declare -x NAME is the same as export NAME, but a plain declare NAME without the option does not create an environment variable.
  • To delete, use unset NAME. If you write unset $NAME, it tries to delete the variable whose name is the value contained in NAME.

Major Environment Variables

VariableWhat it holds
PATHList of directories to search for commands
HOMEHome directory
SHELLLogin shell
USERCurrent user name
PWDCurrent working directory
LANGLanguage and character encoding
TERMTerminal type
PS1Prompt appearance
HISTSIZENumber of commands to keep in history
EDITORDefault editor
HOSTNAMEHost name
LOGNAMELogin name
echo $HOME       # /home/user
echo $USER       # user
echo $PWD        # current directory — same value as the pwd command
echo $LANG       # ko_KR.UTF-8

Variables Often Asked Together

VariableWhat it holds
PS2The secondary prompt shown when a command is not finished (default >)
HISTFILEThe file where history is saved (default ~/.bash_history)
HISTFILESIZENumber of lines to keep in the history file
TMOUTAutomatically logs out after this many seconds without input
MAILPath to the mailbox
DISPLAYWhere X Window screens are shown
OLDPWDThe previous working directory — where cd - goes back to
  • HISTSIZE is the number to remember in memory, and HISTFILESIZE is the number to keep in the file. The names are similar, so questions swap them.
  • USER and LOGNAME usually hold the same value.

PS1 — Prompt Appearance

echo $PS1
# [\u@\h \W]\$
# On screen it looks like this →  [user@server1 ~]$
SymbolValue it becomes
\uUser name (user)
\hHost name (host)
\wThe full path of the current directory
\WOnly the last name of the current directory
\$# if root, $ for a regular user
\d / \tDate / time (24-hour)
\!History number
  • \w and \W are distinguished by case. When you are in /usr/local/bin, \w shows /usr/local/bin and \W shows bin.
  • A prompt ending in # means you are working as root. \$ is what creates this distinction.

PATH — Where Are Commands Looked Up?

echo $PATH
# /usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin
#                └ separated by colons (:)
  • When you type ls, the shell searches the directories listed in PATH in order from the front to find the executable.
  • The separator is the colon (:). This differs from Windows, which uses a semicolon.
  • Paths earlier in the list are searched first. If commands with the same name exist in several places, the earlier one wins.
export PATH=$PATH:/opt/myapp/bin      # append at the end (recommended)
export PATH=/opt/myapp/bin:$PATH      # prepend (to take priority)
which ls                              # /usr/bin/ls — the location actually found

⚠️ If you leave out $PATH, as in export PATH=/opt/bin, all the existing paths vanish and even ls will not run. Always include $PATH:.

  • As a rule, the current directory (.) should not be put in PATH. If a malicious file with the same name is planted, that is what would run. That is why scripts in the current location are run with a path, like ./script.sh.

What Happens When It Is Not in PATH

ls -l backup.sh
# -rwxr-xr-x 1 user user 120 Oct 14 09:00 backup.sh
backup.sh
# bash: backup.sh: command not found
./backup.sh
# backup start...
  • The file is right in front of you and has execute permission, yet it is not found. This is because the shell searches only the places listed in PATH, not the current directory.
MessageCause
command not foundThat name is not in any PATH directory
Permission deniedIt was found, but has no execute permission (x)
  • which tells you the location of the executable found in PATH, and type also tells you whether the name is an alias or a builtin.
  • Builtin commands such as cd, echo, and export run regardless of PATH. So even if you have broken PATH, you can revive it by typing export PATH=/usr/bin:/bin.

Special Variables

VariableMeaning
$?Exit status of the previous command (0 means success)
$$PID of the current shell
$0Name of the running shell or script
$!PID of the last background job
ls /nonexistent
echo $?          # 2  ← non-zero means failure
ls /etc
echo $?          # 0  ← success
  • If $? is 0, it succeeded. A non-zero value means an error. This is the opposite of ordinary true/false, so it is easy to get confused.
$? valueMeaning
0Success
1General failure — e.g., grep found no matching lines
2Usage error, etc. — e.g., ls could not access the specified file
126Found but cannot be executed (no permission)
127Command not found (command not found)
130Interrupted with Ctrl+C
grep root /etc/passwd > /dev/null
echo $?        # 0
echo $?        # 0     ← this is the result of the echo just run. The grep value has already been overwritten
echo $$        # 2314  ← PID of the current shell
sleep 100 &
echo $!        # 2377  ← PID of the sleep just sent to the background
  • There is only one thing to memorize — only 0 is success; everything else is failure. The value range is 0 to 255, and the detailed meaning of non-zero values varies by command.
  • $? remembers only the one previous command. To check it, read it right away without putting another command in between.

Variables Disappear When You Leave the Shell

export PATH=$PATH:/opt/bin     # valid only in this shell right now
How it was createdHow long it lives
NAME=value command or env NAME=value commandFor that one command only
NAME=valueThe current shell
export NAME=valueThe current shell and the children launched from it
Written in a configuration file (~/.bashrc, etc.)Recreated at every login
  • A variable created with a command disappears when you close the terminal.
  • To keep using it, you must write it in a configuration file — ~/.bashrc or ~/.bash_profile. That is tomorrow's topic.

Tomorrow we cover when and in what order these variables are read: the shell environment configuration files.

📖 Glossary

  • Shell variable : A variable valid only inside the current shell. It is not passed to child processes.
  • Environment variable : A variable passed down to child processes. Created with export.
  • export : The command that promotes a shell variable to an environment variable.
  • set : The command that shows both shell variables and environment variables.
  • env : The command that shows only environment variables.
  • PATH : The list of directories to search for executables. Separated by colons.
  • PS1 : The environment variable that defines the appearance of the prompt.
  • $? : A special variable holding the exit status of the previous command. 0 means success.

📝 Practice Questions

Click a choice to reveal the answer and explanation.

Question 1

Which of the following commands turns a shell variable into an environment variable so that it is also passed to child processes?

Question 2

Which of the following environment variables holds the list of directories to search for executables?

Question 3

Which of the following characters separates the directories in the PATH environment variable?

Question 4

Which of the following commands prints only environment variables?

Question 5

Which of the following is a correct variable declaration?

PreviousWhat Is a Shell?Week 5 · Day 1Next Environment Configuration FilesWeek 5 · Day 3

Official references

  • Linux Master 2 official exam syllabus(opens in a new tab)

On this page

  • Key Points
  • Creating Variables
  • Naming Rules and Braces
  • Values That Change Depending on Quotes
  • Shell Variables vs Environment Variables
  • Check It Yourself: Is It Visible in the Child Shell?
  • More Commands for Working with Variables
  • Major Environment Variables
  • Variables Often Asked Together
  • PS1 — Prompt Appearance
  • PATH — Where Are Commands Looked Up?
  • What Happens When It Is Not in PATH
  • Special Variables
  • Variables Disappear When You Leave the Shell
  • Glossary
  • Practice Questions