T6 Linux and Bash · Lesson 7
Environment variables
The settings every program carries: shell variables and how to use them safely, the environment and export, how PATH decides which program a name means, settings that last in .bashrc and source, aliases, and the variables and prompt that shape your terminal.
- make, use and remove shell variables, quoting them safely
- pass settings to programs with export, and read them with env
- say how PATH finds a command, and add a folder to it
- keep settings in .bashrc, and load a file with source
- make short names with alias, and know where they work
- use HOME, PWD, USER and friends, defaults, and your prompt
The back cover
Every program carries a set of settings, such as where your home folder is, which language you use and where to look for commands. The shell keeps them as variables, and passes some of them on to each program it starts.
These pages show shell variables and how to use them safely, and the environment that every child gets a copy of. They show how PATH decides which program a name means, and how settings last in .bashrc. They show aliases, the shell's own useful variables, and how to set your own prompt.
Before you start
The story: The slip in every pocket
Every worker in the Underway carries a slip of settings: where home is, which tool sheds to try, and in what order. The new tool shed by the east gate was finished last week, and the tools in it work perfectly. Yet when anyone asks for one by name, the tube answers that it does not exist.
Corin wrote the shed on his own slip, and it worked, until he walked through the next door.
Warden Rao takes his slip and reads it. "Those who go through a door get a copy of your slip," she says. "Only if you marked it to be copied. And nobody at all gets it tomorrow, unless it is written in the book by the gate."
You have already used names that start with a $: $? for the last status, $$ for the shell's own number, $HOME for your home folder. They are variables, the shell's way of remembering a value under a name. This lesson shows how to make your own, how programs receive them, and how the settings that shape every terminal are kept.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| Names that hold values. | let count = 0 | Shell variables work the same way. |
| $HOME and ~. | echo $HOME | One of many settings. |
| Quotes. | "$HOME" and '$HOME' | Double quotes let a variable in. |
| Processes and children. | a command you run | Children get a copy of some settings. |
| type and which. | which ls | They search PATH. |
| command not found. | status 127 | Often a PATH problem. |
| Running a script by its path. | ./pump.sh | PATH makes the path unneeded. |
| bash file. | bash settings.sh | Runs in a child; source does not. |
| Hidden files. | .bashrc | Where settings are kept. |
| The umask. | lasts until the shell ends | So do variables, unless kept. |
By the end of this lesson you will be able to:
- make, use and remove shell variables, quoting them safely;
- pass settings to programs with export, and read them with env;
- say how PATH finds a command, and add a folder to it;
- keep settings in .bashrc, and load a file with source;
- make short names with alias, and know where they work;
- use HOME, PWD, USER and friends, defaults, and your prompt.
How to follow this lesson
Each block starts a fresh shell, so a variable set in one block is gone in the next, as it would be in a new terminal. That is the lesson's own subject: by the end, you will know how to make a setting outlive the shell that set it.
In one line
A variable is a value kept under a name; this lesson shows how to make them, pass them to programs, and keep them from one terminal to the next.
Shell variables
At a glance
A variable is a labelled box: a name, and a value kept inside it. You put a value in with = and take it out with a $ in front of the name.
The shell puts the value in place of the name before the command runs. There must be no spaces round the =, and ${name} keeps the name apart from letters that follow. A name with no value gives empty text. Double quotes keep a value with spaces in one piece, and unset removes a variable.
Take a guess: Is there a tool that warns you about a variable left without quotes?
A variable is a labelled box: a name, and a value kept inside it. You put a value in with = and take it out with a $ in front of the name. The shell then puts the value in place of the name, before the command runs:
pump=north
echo $pump
echo "the $pump pump"
north
the north pump
A name with a value kept in the shell. You set it with name=value, and the shell replaces $name with the value wherever it appears. Every value is text.
There must be no spaces round the =. With a space, the shell reads the first word as a command's name:
pump = north
pump= north
bash: line 1: pump: command not found
bash: line 2: north: command not found
The second line is a subtler slip. pump= with nothing after it sets pump to an empty value for one command, and that command is north, which does not exist.
Braces, and names that are not there
When letters follow the name, the shell cannot tell where the name ends. Braces mark the end: ${pump}. A name that has no value gives empty text, with no error at all:
pump=north
echo "the ${pump}side pump"
echo "the $pumpside pump"
the northside pump
the pump
The last line looked for a variable named pumpside, found none, and put nothing there. That silence is why misspelt names are a common bug.
Quote your variables
A value can hold spaces. Without quotes, the shell splits the value at its spaces into separate words, just as it splits what you type. Put the variable in double quotes, and it stays one word:
name="Asha Rao"
touch $name
ls
rm Asha Rao
touch "$name"
ls
Asha Rao
'Asha Rao'
The first touch received two words, Asha and Rao, and made two files. The second received one word, and made one file with a space in its name. The habit that prevents this is simple to state: write "$name", in double quotes, unless you have a reason not to.
Removing and protecting
unset removes a variable. readonly makes one that cannot be changed:
greeting=Hello
unset greeting
echo "[$greeting]"
readonly level=3
level=4
echo $level
[]
bash: line 5: level: readonly variable
3
| Written | It does |
|---|---|
name=value | sets the variable, with no spaces round = |
$name or ${name} | the value; braces mark where the name ends |
"$name" | the value as one word, spaces and all |
unset name | removes it |
readonly name=value | sets it, and stops later changes |
Names may use letters, digits and the underscore, but cannot start with a digit. By habit, your own variables use small letters, and the settings of the system use capitals, as in HOME and PATH.
Worked example 1
Warden Rao wants one report line for a pump: its name, its pressure in bar, and the word bar written straight after the number with no space, such as 12bar.
What we have: a pump named north, at 12 bar
What we need: the line pump north at 12bar
The plan: keep each value in a variable; use braces where letters follow the name; quote the whole line
pump=north
pressure=12
echo "pump $pump at ${pressure}bar"
pump north at 12bar
- Without the braces, the shell would look for a variable named pressurebar, which does not exist.
The line reads pump north at 12bar.
Check: the number and bar touch, and the pump's name is in place.
A path that fails: echo "pump $pump at $pressurebar". It prints pump north at, with nothing after, because pressurebar has no value.
When you are stuck: a variable gives nothing, or the wrong thing
command not found on the line that sets it: take out the spaces round =.
Empty: check the spelling, or letters running into the name. Use braces.
Split into pieces, or a file name broken in two: put the variable in double quotes.
Gone in the next block, or the next terminal: that is normal; the next sections show how to keep it.
Your turn
fruit=mango
echo "${fruit}es and $fruit"
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
mangoes and mango
- The braces end the name before es.
- $fruit alone gives mango.
It prints mangoes and mango.
Why does city = Pune fail?Tap to reveal
- With spaces, the shell reads city as a command's name.
Because = must have no spaces round it.
Why write "$name" and not $name?Tap to reveal
- Without quotes, a value with spaces is split into words.
So that the value stays one word, spaces and all.
Did you know?
Named variables from Stephen Bourne
Named variables came with the Bourne shell. In Seventh Edition Unix, released in 1979, it replaced the first shell, the Thompson shell, and took its name, sh. Stephen Bourne's guide to it says the shell provides string-valued variables, whose names begin with a letter and consist of letters, digits and underscores. His first example was user=fred.
Why it fits here: It shows where this topic's name=value comes from: Stephen Bourne's shell of 1979, with names made of letters, digits and underscores.
Sources: S. R. Bourne: An Introduction to the UNIX Shell; FreeBSD manual: sh(1); Wikipedia: Bourne shell
A checker for missing quotes
A program can catch a missing pair of quotes. ShellCheck, a checker for shell scripts, reports an unquoted variable as SC2086: double quote to prevent globbing and word splitting. Its wiki explains that echo $1 does not just print the first argument. It splits it at spaces, tabs and line feeds, and expands each piece as a pattern, so quoting is the fix it asks for.
Why it fits here: It backs this topic's rule to quote variables: ShellCheck flags every unquoted one, as warning SC2086.
Source: ShellCheck wiki: SC2086
In one line
Set a variable with name=value, with no spaces round =, and use it as $name, or ${name} when letters follow. A name with no value gives empty text. Put variables in double quotes so that spaces do not split them; unset removes one.
The environment, and export
At a glance
A variable belongs to the shell that set it. When the shell starts a program, the program does not see the shell's variables unless they were marked to be passed on.
The marked variables, with their values, are the environment, and export marks one. Every child gets a copy, so its changes never reach its parent. The command env lists the environment, printenv name prints one value, and name=value command gives a single command a setting of its own. Programs read it to learn your language, your home and more.
Take a guess: Why do system variables have names in capitals, like PATH and HOME?
A variable belongs to the shell that set it. When the shell starts a program, the program is a new process, and it does not see the shell's variables unless they were marked to be passed on. Those marked variables, with their values, are the environment, and every child gets a copy.
A second bash, started with bash -c, is an easy child to test with. Watch what it sees before and after the mark:
city=Pune
bash -c 'echo "child sees: [$city]"'
export city
bash -c 'echo "child sees: [$city]"'
child sees: []
child sees: [Pune]
The single quotes kept the outer shell from filling in $city, so the child did it itself. The first child saw nothing. export marked city to be passed on, and the second child saw Pune.
A variable marked with export, so that every program the shell starts receives a copy of it. Programs read their settings this way: HOME, PATH and LANG are environment variables.
This is the slip in every pocket from the scene: a crew going through a door gets a copy, but only of what was marked to be copied. A copy is all it gets, too. A change that a child makes to its copy never reaches the parent.
Seeing the environment
The command env prints every environment variable, one name=value to a line. printenv prints the value of the names you give it, and fails, with status 1, for a name that is not in the environment:
export station=north
env | grep station
printenv station
printenv nothing
echo $?
station=north
north
1
env | sort | head -n 3
HOME=/home/asha
LANG=C.UTF-8
PATH=/usr/bin:/bin
Every name above came from the environment that this shell itself was given when it started.
A setting for one command
Write an assignment just before a command, on the same line, and only that command gets it, in its environment. The shell's own variable is not touched:
gauge=12 bash -c 'echo $gauge'
echo "[$gauge]"
12
[]
This is common with tools that read settings, such as LANG=C sort names.txt, which sorts by plain character codes for that one run.
| Written | It does |
|---|---|
name=value | a variable for this shell only |
export name or export name=value | also a copy for every child |
name=value command | a copy for that one command only |
env | every environment variable |
printenv name | one environment variable's value |
Worked example 2
A crew is about to be sent through a door, a child shell, and must know which station it serves. Show that the child does not see an unmarked station, then mark it, and send another crew.
What we have: a station named east, and child shells started with bash -c
What we need: the second child seeing east
The plan: set it; start a child that prints it; export it; start another
station=east
bash -c 'echo "crew: [$station]"'
export station
bash -c 'echo "crew: [$station]"'
crew: []
crew: [east]
- Only after export did the setting travel with the crew.
The first crew sees nothing; after export, the second sees east.
Check: the brackets show the value each child received.
A path that fails: setting station inside the child, in bash -c. That gives the child a value of its own, which ends with it, and the parent never learns it.
When you are stuck: a program does not see your setting
Did you export it? A plain name=value stays in this shell.
Is it in env? Run env | grep name.
Set in a child, gone in the parent: children cannot change their parent's variables.
Gone in a new terminal: export lasts only as long as this shell; the startup section shows how to keep it.
Your turn
pump=north
bash -c 'echo "[$pump]"'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[]
- pump was never exported.
- So the child has no pump.
It prints [].
How do you give the setting LANG=C to one sort command only?Tap to reveal
- Write the assignment before the command, on the same line.
LANG=C sort file.
Which command prints every environment variable?Tap to reveal
- One name=value to a line.
env, or printenv with no names.
Did you know?
Capitals for the system, small letters for you
The capitals in PATH and HOME follow a rule. POSIX, the standard for Unix systems, says the names of its environment variables are made of capital letters, digits and the underscore, and do not begin with a digit. It reserves names with small letters for applications, which can use them without changing how the standard tools behave. So your own names, such as backup_dir, cannot upset those tools.
Why it fits here: It answers this topic's question: POSIX keeps capital names for the system and leaves small-letter names to your own programs.
Web apps keep their settings here
The environment also carries the settings of web apps. The Twelve-Factor App, a guide written by Adam Wiggins from work on the Heroku platform, says such an app stores its config in environment variables. That includes credentials for outside services. Env vars are easy to change between deploys without changing any code, and are less likely than config files to be saved into the project's code by accident.
Why it fits here: It shows a real use of this topic's environment: web servers read their settings, credentials included, from it.
Sources: Adam Wiggins: The Twelve-Factor App; The Twelve-Factor App: III. Config
In one line
Only exported variables, the environment, are copied to the programs a shell starts; export marks them. A child's changes never reach its parent. env lists the environment, printenv name prints one value, and name=value command gives one command a setting.
How commands are found: PATH
At a glance
When you type ls, the shell does not search the whole disk. It looks in a short list of folders, in order, and runs the first file with that name that it finds.
That list is the environment variable PATH, with its folders separated by colons. The commands which and type -a show where a name leads. To add a folder, write export PATH="folder:$PATH", which keeps the rest; replacing the list loses every other command. A name with a slash in it, such as ./pump.sh, skips PATH altogether.
Take a guess: Can a single stray colon in PATH make the shell look in the current folder?
When you type ls, how does the shell know which file to run? Not by searching the whole disk. It looks in a short list of folders, in order, and runs the first file with that name that it finds. That list is the environment variable PATH.
echo $PATH
which ls
type -a ls
/usr/bin:/bin
/usr/bin/ls
ls is /usr/bin/ls
ls is /bin/ls
The folders are separated by colons. Here there are two, /usr/bin and /bin, and a real machine has several more. which shows the file that a name would run. type -a lists every match, in order; the first is the one that runs.
An environment variable that lists folders, separated by colons. A command name with no slash in it is looked for in each folder in turn, and the first match runs. If none matches, the shell says command not found.
Remember from the permissions lesson that a script in the current folder needs ./ in front of it. That is because the current folder is not in PATH. A name with a slash in it, such as ./pump.sh, is used as a path, and PATH is not searched at all.
Adding a folder
This is the east shed from the scene: a folder of working tools that nobody can call by name, because it is not in the list. Adding it to the front of PATH fixes that. Note the old value, $PATH, kept at the end, so that every other folder stays on the list:
In a folder with bin/tool, a runnable script
tool
export PATH="$HOME/shop/bin:$PATH"
tool
which tool
echo $PATH
bash: line 1: tool: command not found
hello from the east shed
/home/asha/shop/bin/tool
/home/asha/shop/bin:/usr/bin:/bin
A folder at the front is searched first, so its tools win over others of the same name. At the end, it is searched last.
Never replace PATH
Assigning a new list without $PATH in it throws the old folders away. Then even ls cannot be found, for the rest of that shell:
PATH=$HOME/shop/bin
ls
bash: line 2: ls: command not found
The cure is to open a new terminal, which starts with the usual PATH, or to type the old list back in full.
| Written | It does |
|---|---|
echo $PATH | shows the list |
which name, type -a name | shows which file a name runs |
export PATH="$HOME/bin:$PATH" | adds a folder at the front, keeping the rest |
export PATH="$PATH:$HOME/bin" | adds it at the end |
./name | runs a file here, without PATH |
Worked example 3
The east shed's tool works by its path, bin/tool, but nobody can run it by name. Make tool work by name in this shell, and show which file runs, without losing ls.
What we have: a script bin/tool, and a PATH without its folder
What we need: tool working by name, and ls still working
The plan: add the folder's full path to the front of PATH, keeping $PATH; check with which and with ls
In a folder with bin/tool, a runnable script
export PATH="$HOME/shop/bin:$PATH"
tool
which tool
ls
hello from the east shed
/home/asha/shop/bin/tool
bin
- The full path, beginning with $HOME, works from any folder; a relative bin would only work while you stand here.
export PATH="$HOME/shop/bin:$PATH" makes tool work.
Check: which tool names the file in the east shed, and ls still lists the folder.
A path that fails: PATH=bin. It replaces the list, so tool works, but ls, and every other program, is no longer found.
When you are stuck: a command is not found, or the wrong one runs
command not found: check the spelling, then echo $PATH: is its folder there?
A script here: run it as ./name, or add its folder to PATH.
The wrong version runs: type -a name lists every match; the first wins.
Nothing works any more: PATH was replaced. Open a new terminal.
Your turn
PATH is /usr/local/bin:/usr/bin, and a program named pump is in both folders. Which one runs?Tap to reveal
- The folders are searched in order.
- The first match wins.
The one in /usr/local/bin.
Why does a script in the current folder need ./ in front?Tap to reveal
- The current folder is not in PATH.
- A name with a slash is used as a path.
Because the current folder is not in PATH.
PATH="/nowhere"
ls
echo $?
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
bash: line 2: ls: command not found
127
- The new PATH holds one folder, which has no ls.
- Not found gives 127.
It prints the command not found error, then 127.
Did you know?
One colon too many
An empty entry in PATH means the current folder. POSIX calls this a legacy feature: it appears as two colons side by side, a colon at the start, or a colon at the end. So a line like PATH=$PATH: quietly makes the shell look in whatever folder you are in. The standard asks programs that want the current folder to write it as a dot instead.
Why it fits here: It answers this topic's question: one stray colon in PATH adds the current folder to the search.
bash remembers where it looked
bash does not search PATH every time. Its manual says it keeps a hash table of the full paths of programs it has found, and searches PATH only for a name that is not in the table. Unless the checkhash option is on, it does not check that a remembered program is still there. The command hash -r clears the table, and so does any change to PATH.
Why it fits here: It explains a surprise in this topic's search: bash remembers where it found each program, and hash -r makes it look again.
In one line
PATH lists folders, separated by colons; a command name is looked for in each in turn, and the first match runs. Add a folder with export PATH="folder:$PATH", never by replacing the list. A name with a slash skips PATH, which is why scripts here need ./.
Settings that last: source and .bashrc
At a glance
Every setting so far lasts only as long as its shell. Close the terminal, and the variables, the exports and the new PATH are gone.
To keep a setting, write it in a file that the shell reads each time it starts. The command bash file runs a file in a child shell, whose settings end with it, while source file, or the shorter . file, runs it in this shell. Lasting settings go in ~/.bashrc, which every new terminal reads; add lines with >>, and source it to load a change now.
Take a guess: What do the letters rc in .bashrc stand for?
Every setting so far lasted only as long as its shell. Close the terminal, open a new one, and the variables, the export and the new PATH are gone. To keep a setting, you write it in a file that the shell reads every time it starts: the book by the gate, in the scene.
Running a file, or reading it in
There are two ways to run a file of commands, and the difference matters here. bash file runs it in a new child shell, whose settings end with it. source file runs it in the current shell, so its settings stay. A single dot, . file, means the same as source:
printf 'pump=south\n' > settings.sh
bash settings.sh
echo "[$pump]"
source settings.sh
echo "[$pump]"
[]
[south]
A builtin that reads a file and runs its commands in the current shell, as if you had typed them. Its other name is a single dot. Variables, exports and aliases that the file sets remain afterwards.
~/.bashrc
The file to put lasting settings in is ~/.bashrc, a hidden file in your home folder. Every interactive bash that is not a login shell reads it when it starts, which on a desktop means every new terminal window. A login shell, such as the one you get when you connect to a server, reads ~/.profile instead, and on Ubuntu that file reads ~/.bashrc in turn.
Here a fresh interactive bash started with a .bashrc that holds two lines, an alias and an export. Both were there at the first prompt, with nothing typed to load them:
~/.bashrc
alias greet='echo Namaste'
export PUMP=north
Typed in a new terminal that read that .bashrc
asha@tower:~/shop$ greet
Namaste
asha@tower:~/shop$ echo $PUMP
north
asha@tower:~/shop$
When you change ~/.bashrc, terminals that are already open do not notice; they read it only when they started. Load the new version into the current one with source ~/.bashrc, as the worked example does.
| File | Read by | Holds |
|---|---|---|
~/.bashrc | every interactive bash that is not a login shell | aliases, exports, PATH, the prompt |
~/.profile | login shells, such as a connection to a server | settings for the whole session |
/etc/profile, /etc/bash.bashrc | every user's shells | the machine's own defaults |
Add, do not replace
To add a line to ~/.bashrc from the command line, use >>, as in the worked example. A single > would replace the whole file with that one line, and every setting in it would be lost.
Worked example 4
Write the east shed into the book by the gate: add the line that puts ~/shop/bin at the front of PATH to ~/.bashrc, load it into this shell, and show that tool now works by name.
What we have: a runnable script ~/shop/bin/tool, and an empty ~/.bashrc
What we need: the line kept in ~/.bashrc, and tool working now
The plan: append the export line with >>, quoting it with single quotes so that $HOME and $PATH stay as written; then source the file
In a folder with bin/tool, a runnable script
echo 'export PATH="$HOME/shop/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
tool
tail -n 1 ~/.bashrc
hello from the east shed
export PATH="$HOME/shop/bin:$PATH"
- The single quotes kept $HOME and $PATH as words in the file, so that each new shell fills them in when it reads the file. Every new terminal will now have the east shed on its PATH.
The line is in ~/.bashrc, and tool runs.
Check: tail shows the line exactly as written, with its $ signs.
A path that fails: writing the line with double quotes outside. The shell would fill in $PATH now, and fix today's list into the file for good.
When you are stuck: a setting does not last, or does not load
Gone in a new terminal: it was typed, not written in ~/.bashrc.
Written, but this terminal ignores it: source ~/.bashrc, or open a new one.
bash file kept nothing: it ran in a child. Use source file.
A server ignores your .bashrc: a login shell reads ~/.profile; check that it reads .bashrc.
Your turn
printf 'x=5\n' > s.sh
bash s.sh
echo "[$x]"
. ./s.sh
echo "[$x]"
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
[]
[5]
- bash s.sh runs in a child.
- The dot reads it into this shell.
It prints [], then [5].
You added an alias to ~/.bashrc. How do you use it in the terminal that is already open?Tap to reveal
- The open shell read the file when it started.
source ~/.bashrc.
Why use >> and not > to add a line to ~/.bashrc?Tap to reveal
- > replaces the whole file.
Because > would wipe every other setting.
Did you know?
rc means run commands
The rc at the end of .bashrc is a fossil. Around 1963 Louis Pouzin wrote RUNCOM for the CTSS time-sharing system, a tool that ran a file of commands. Pouzin recalled that people could then go home in the evening and leave long runcoms working overnight. Brian Kernighan and Dennis Ritchie later wrote that such a file came to be called a runcom, and that rc in Unix is a fossil from that usage.
Why it fits here: It answers this topic's question: the rc of .bashrc means run commands, from Louis Pouzin's RUNCOM of about 1963.
Sources: Wikipedia: RUNCOM; Louis Pouzin: The Origin of the Shell
source came from the C shell
The word source comes from the C shell. Wikipedia notes that the dot command, which runs a file's commands in the current shell, is provided in the C shell as source, and that the C shell is where the command first appeared. POSIX names only the dot, as the command that executes commands in the current environment. bash accepts both, and its manual calls source a synonym for the dot.
Why it fits here: It explains this topic's two names for one job: the dot from the Bourne shell and POSIX, and source from the C shell.
Sources: Wikipedia: Dot (command); FreeBSD manual: tcsh(1); POSIX.1-2024: Shell Command Language; GNU Bash manual: Bash Builtin Commands
In one line
bash file runs a file in a child, whose settings end with it; source file, or . file, runs it in this shell. Keep lasting settings in ~/.bashrc, which every new interactive terminal reads; add lines with >>, and source it to load changes now.
Short names: alias
At a glance
Some commands you type twenty times a day. An alias gives one of them a short name of your own.
Write alias name='text', and when you type the alias as the first word of a command, the shell swaps in the text. So alias ll='ls -l' turns ll into a long listing. The command alias lists your aliases, and unalias removes one. Keep them in ~/.bashrc so that they last. Aliases are for people typing at a prompt: scripts do not expand them.
Take a guess: On Ubuntu, does ll work before you make any alias?
Some commands you type twenty times a day. An alias gives one a short name of your own. When you type the alias as the first word of a command, the shell swaps in the text it stands for. This was typed at a real prompt:
Typed: an alias made, used and removed
asha@tower:~/shop$ alias greet='echo Namaste'
asha@tower:~/shop$ greet
Namaste
asha@tower:~/shop$ unalias greet
asha@tower:~/shop$ greet
bash: greet: command not found
asha@tower:~/shop$
A short name that the shell replaces with longer text when it is the first word of a command you type. alias name='text' makes one, and unalias name removes it.
Some aliases are so common that many people's .bashrc files have them:
| Alias | Stands for | Why |
|---|---|---|
ll | ls -l | the long listing, in two letters |
la | ls -A | hidden files too |
rm | rm -i | a question before each removal |
.. | cd .. | up one level |
alias with no arguments lists every alias, and alias with a name shows that one. The listing is in the very form that defines it, which makes it easy to copy into ~/.bashrc:
alias ll='ls -l' la='ls -A'
alias
alias ll
unalias la
alias
alias la='ls -A'
alias ll='ls -l'
alias ll='ls -l'
alias ll='ls -l'
Not in scripts
Aliases are for people typing. When bash runs a script, it does not expand them, and that includes every block on this page. So the alias is made, but using it fails:
alias ll='ls -l'
ll
bash: line 2: ll: command not found
In a script, write the command out in full, or use a function, which the next lesson teaches.
Worked example 5
Corin types ls -l all day, and wants ll to mean it in every terminal he opens. Show what to put where, and how to check it.
What we have: the command ls -l, and Corin's ~/.bashrc
What we need: ll working in every new terminal
The plan: an alias makes ll; ~/.bashrc makes it last; source loads it now; alias ll shows it
echo "alias ll='ls -l'" >> ~/.bashrc
source ~/.bashrc
alias ll
alias ll='ls -l'
- The alias is now in this shell and in the file that every new terminal reads. In a real terminal, typing ll then runs ls -l; this page, being a script, will not expand it.
Add alias ll='ls -l' to ~/.bashrc and source it.
Check: alias ll shows the definition in this shell.
A path that fails: typing the alias at the prompt only. It works until that terminal closes, and the next terminal has never heard of it.
When you are stuck: an alias does not work
command not found in a script: scripts do not expand aliases. Write the command out.
Gone in a new terminal: it was not written in ~/.bashrc.
Something else runs: alias name shows what the alias stands for; type name shows how the shell reads the name.
You want the real command for once: put a backslash before it, as in \rm, which skips the alias.
Your turn
What does alias print with no arguments?Tap to reveal
- It lists every alias, in the form that defines it.
Every alias, as alias name='text' lines.
Why does an alias fail inside a script?Tap to reveal
- bash does not expand aliases when it is not interactive.
Because scripts do not expand aliases.
alias up='cd ..'
alias up
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
alias up='cd ..'
- alias with a name prints that alias's definition.
It prints alias up='cd ..'.
Did you know?
ll is already there
On Ubuntu, ll works before you make any alias. The .bashrc that Ubuntu copies into each new user's home already defines three: ll as ls -alF, la as ls -A and l as ls -CF. The -a shows names that start with a dot, and -F marks each name with its kind, such as a slash after a folder. Typing alias in a new Ubuntu terminal shows them.
Why it fits here: It answers this topic's question: Ubuntu's own .bashrc already gives ll, la and l as aliases.
Sources: Ubuntu bash package: debian/skel.bashrc; Linux man-pages: useradd(8); GNU Coreutils manual: Which files are listed; GNU Coreutils manual: General output formatting
The manual prefers functions
The bash manual itself prefers functions to aliases. It says there is no way to use arguments inside an alias's replacement text, as there is in csh, and that a shell function should be used when arguments are needed. It ends its section with plain advice: for almost every purpose, shell functions are preferable to aliases.
Why it fits here: It points past this topic's aliases: when a short name needs arguments, the bash manual says to write a function.
Source: GNU Bash manual: Aliases
In one line
alias name='text' gives a long command a short name, for people typing at a prompt; alias lists them, unalias removes one. Keep aliases in ~/.bashrc so that they last. Scripts do not expand aliases.
Useful variables, and your prompt
At a glance
The shell keeps a number of variables for you, most of them in the environment. HOME is your home folder, USER your name, PWD the folder you are in, and PS1 your prompt.
Two tricks work with any variable. ${#name} counts the characters of its value, and ${name:-default} gives a default when the value is empty. The prompt PS1 can hold codes that bash fills in: \u for your user name, \h for the machine's name and \w for the folder you are in.
Take a guess: Is there a variable that gives a new number each time you read it?
The shell keeps a number of variables for you, most of them in the environment. You have met several. Here they are together, with a few tricks for using any variable.
echo $HOME
echo $USER
echo $SHELL
echo $PWD
cd /tmp
echo $PWD $OLDPWD
/home/asha
asha
/bin/bash
/home/asha/shop
/tmp /home/asha/shop
| Variable | Holds | Changed by |
|---|---|---|
HOME | your home folder; cd with no folder goes here | the system, at login |
USER | your user name | the system, at login |
SHELL | your login shell | the system |
PWD | the current folder | cd, every time |
OLDPWD | the folder before the last cd; cd - uses it | cd |
PATH | where commands are looked for | you, in ~/.bashrc |
LANG | your language and character set | the system, or you |
PS1 | the look of your prompt | you, in ~/.bashrc |
RANDOM | a new random number, 0 to 32767, each time it is read | the shell |
Two tricks for any variable
${#name} gives the number of characters in a value. ${name:-default} gives the value, or the default text if the variable is empty or not set, which saves an if in many scripts:
echo ${#HOME}
echo "${PUMP:-unnamed}"
PUMP=north
echo "${PUMP:-unnamed}"
10
unnamed
north
/home/asha is 10 characters. The default text was used only while PUMP had no value.
Your prompt: PS1
The prompt itself is a variable, PS1. Set it, and the next prompt changes at once. This was typed in a real terminal:
Typed: a new value for PS1
asha@tower:~/shop$ PS1='pump> '
pump> echo hi
hi
pump>
In PS1, a few backslash codes are filled in each time the prompt is drawn: \u is the user, \h is the machine's name, and \w is the current folder, with ~ for home. The prompt that this school shows, asha@tower:~/shop$, comes from PS1='\u@\h:\w\$ '. Put your PS1 in ~/.bashrc to keep it.
Worked example 6
A night report must start with who wrote it and from which folder, and name the pump, or the word unnamed if no pump was given. Write the line with variables only.
What we have: the variables USER and PWD, and a PUMP that may be empty
What we need: a line such as asha in /home/asha/shop: pump unnamed
The plan: USER and PWD give the person and the folder; ${PUMP:-unnamed} gives the pump or the default
echo "$USER in $PWD: pump ${PUMP:-unnamed}"
PUMP=east
echo "$USER in $PWD: pump ${PUMP:-unnamed}"
asha in /home/asha/shop: pump unnamed
asha in /home/asha/shop: pump east
- The same line works with and without a pump, because the default fills the gap.
echo "$USER in $PWD: pump ${PUMP:-unnamed}".
Check: the first line shows the default, the second the pump's name.
A path that fails: echo "$USER in $PWD: pump $PUMP". With no PUMP, the line ends in pump and a space, and the report looks broken.
When you are stuck: a variable is not what you expected
HOME, USER and the rest come from the system; print them with echo to see.
PWD and OLDPWD change with every cd.
An empty value breaks a sentence: give it a default with ${name:-text}.
A new prompt is gone in the next terminal: put PS1 in ~/.bashrc.
Your turn
word=pump
echo ${#word}
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4
- ${#word} counts the characters of pump.
It prints 4.
After cd /tmp, what does $OLDPWD hold?Tap to reveal
- OLDPWD is the folder before the last cd.
The folder you were in before the cd.
What does ${STATION:-north} give when STATION is not set?Tap to reveal
- The text after :- is the default.
north.
Did you know?
RANDOM and its seed
Some variables change by themselves. The bash manual says each time RANDOM is read, it gives a random whole number from 0 to 32,767. Giving RANDOM a value seeds it, and seeding it with the same number produces the same sequence again. So RANDOM=42 at the top of a test script makes its random choices repeat exactly on every run.
Why it fits here: It answers this topic's question: RANDOM gives a new number each time it is read, from 0 to 32,767.
Source: GNU Bash manual: Bash Variables
One colon, two meanings
In ${name:-default}, the colon matters. The bash manual says that with the colon, the default is used when the variable is unset or empty. Without it, as in ${name-default}, the test is only for a variable that is unset, so an empty value stays empty. So when name holds empty text, ${name:-guest} gives guest, while ${name-guest} gives nothing.
Why it fits here: It sharpens this topic's ${name:-default}: the colon makes the default cover empty values as well as unset ones.
In one line
The shell keeps HOME, USER, SHELL, PWD, OLDPWD, PATH, LANG and PS1 for you. ${#name} counts a value's characters, and ${name:-default} gives a default for an empty one. PS1 is your prompt, with \u, \h and \w filled in.
Where it is used
Settings in variables are how programs are told what to do without changing them. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| variables | every script | a folder name used ten times, set once |
export | settings for programs | a server told its port in a variable |
name=value command | one run with a different setting | LANG=C sort names.txt |
PATH | tools installed in your home | a folder of your own scripts |
~/.bashrc | every new terminal | your PATH, aliases and prompt |
source | loading settings now | a project's settings file, before work |
alias | fewer keystrokes | ll for ls -l |
${name:-default} | scripts that must not break | a default folder when none is given |
Mistakes and debugging
These are the slips that people meet most often with variables. Every output below is the real one, from the code shown.
1. Spaces round =
pump = north
bash: line 1: pump: command not found
With spaces, pump is read as a command. The fix: pump=north.
2. A value with spaces and no quotes
dir="pump room"
mkdir $dir
ls
pump room
Two folders were made, pump and room. The fix: mkdir "$dir".
3. Forgetting export
station=east
bash -c 'echo "[$station]"'
[]
The child got no copy. The fix: export station.
4. Replacing PATH
PATH=~/bin
ls
bash: line 2: ls: command not found
Every other folder was thrown away. The fix: PATH="$HOME/bin:$PATH", and a new terminal to recover.
5. Running a settings file with bash
printf 'export PUMP=north\n' > settings.sh
bash settings.sh
echo "[$PUMP]"
[]
The settings were made in a child, and ended with it. The fix: source settings.sh.
6. An alias in a script
alias ll='ls -l'
ll
bash: line 2: ll: command not found
Scripts do not expand aliases. The fix: write ls -l, or use a function.
The debugging corner: print it
When a setting seems wrong, print it before you guess. echo "[$name]" shows a value, with brackets to reveal spaces or emptiness. env | grep NAME shows whether it is exported. echo $PATH and type -a cmd show where a command comes from.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
The lesson in code
pump="north pump" # a variable, quoted for its space
echo "[$pump] ${#pump}" # its value, and its length
export STATION=east # copied to every child
bash -c 'echo "child: $STATION"' # a child sees it
export PATH="$HOME/shop/bin:$PATH" # a folder at the front of PATH
tool # found by name
echo "${GATE:-north}" # a default for an empty name
alias ll='ls -l' # for typing, not for scripts
alias
[north pump] 10
child: east
hello from the east shed
north
alias ll='ls -l'
| When you see | It means | Look at |
|---|---|---|
command not found on name = value | spaces round = | name=value |
| an empty value | a misspelt name, or one never set | echo "[$name]" |
| files split at a space | an unquoted variable | "$name" |
| a child sees nothing | the variable was not exported | export |
command not found for your tool | its folder is not in PATH | echo $PATH |
| nothing works at all | PATH was replaced | a new terminal |
| a setting gone in a new terminal | it was not in ~/.bashrc | source ~/.bashrc |
| an alias not found in a script | scripts do not expand aliases | the full command |
The story: Written by the gate
You mark the setting to be passed on, and now every crew sent through a door has the new shed on its slip. You add it to the list of sheds, in the right place, without losing the others. Then you write it in the book by the gate, which everyone reads on the way in, so that it is there every morning.
The next day the east shed's tools answer to their names, for everyone, with nobody having to ask.
Corin's slip now reads the same as everyone's. He seems slightly disappointed. "That is what a good setting feels like," says the warden.
Reagents gathered: environment variable, export, PATH, source, .bashrc, alias.
Sources
- GNU Bash Reference Manual (GNU Free Documentation License 1.3 or later (the manual's copying notice, read 2026-11-06); facts and ideas only)
- GNU Coreutils manual (GNU Free Documentation License 1.3 or later (the manual's copying notice, read 2026-11-06); facts and ideas only)