Menu

Shells and Shell Scripting

Step 1 of 2 LPIC-1 105.1weight 4

Customize and use the shell environment

“Which startup files Bash reads and when, how variables, PATH, aliases and functions work, and how /etc/skel sets up new users.”

View .md

Every time you open a terminal, Bash quietly runs a handful of files before it shows you a prompt. Those files set your PATH, your prompt, your aliases and your favorite shortcuts. When something “works in one terminal but not in another”, or a variable is missing in a script or after sudo, the answer is almost always in which file ran and which didn’t.

This byte shows you the startup files in order, the difference between shell and environment variables, how to make aliases and functions, how PATH finds commands, and how /etc/skel gives every new user a starting set of these files.

Login shells and non-login shells#

Bash reads different files depending on how it was started. Two questions decide it:

  • Is it a login shell? You get one when you log in on a text console, over SSH, with su - or sudo -i, or when you run bash -l (--login).
  • Is it interactive? A shell that shows you a prompt is interactive. A shell that runs a script is not.

Opening a new terminal window in a desktop, or typing bash inside a shell, usually gives you an interactive non-login shell.

You can check which kind you’re in:

bash
echo $0
shopt login_shell
console
-bash
login_shell    	on

A leading dash in $0 (-bash) means a login shell. In a plain bash subshell you’d see bash and login_shell off.

The startup files, in order#

WhenBash reads
Login shell starts/etc/profile, then the first one found of ~/.bash_profile, ~/.bash_login, ~/.profile
Interactive non-login shell starts/etc/bash.bashrc (Debian/Ubuntu) and ~/.bashrc
Login shell exits~/.bash_logout
Non-interactive shell (a script)none of the above, only the file named in $BASH_ENV if it’s set

The important rule: for a login shell, Bash stops at the first personal file it finds. If you create a ~/.bash_profile on Ubuntu, your ~/.profile (which Ubuntu ships with useful settings) is silently ignored.

What each file is for:

  • /etc/profile: system-wide settings for all users’ login shells: the default PATH, umask, and it runs every *.sh file in /etc/profile.d/. Packages drop their own snippets in /etc/profile.d/ so they don’t have to edit /etc/profile.
  • /etc/bash.bashrc: system-wide settings for interactive Bash shells on Debian and Ubuntu (prompt, checkwinsize, the “command not found” helper). Red Hat, Fedora and their relatives call the same idea /etc/bashrc.
  • ~/.bash_profile, ~/.bash_login, ~/.profile: your personal login settings. ~/.profile is the generic one that other Bourne-style shells like sh and dash also read, so it’s the safest place for environment variables.
  • ~/.bashrc: your personal interactive settings: aliases, functions, prompt, shell options.
  • ~/.bash_logout: commands to run when you leave a login shell, such as clearing the screen.

How the distributions glue them together#

Because a login shell doesn’t read ~/.bashrc by itself, every distribution makes the login file source it. That way your aliases work in both kinds of shell.

On Debian and Ubuntu, /etc/profile sources /etc/bash.bashrc, and the default ~/.profile sources ~/.bashrc:

~/.profile (Debian/Ubuntu)bash
# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
	. "$HOME/.bashrc"
    fi
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

On RHEL and Fedora, the default ~/.bash_profile sources ~/.bashrc, and ~/.bashrc sources /etc/bashrc:

~/.bash_profile (RHEL/Fedora)bash
# Get the aliases and functions
if [ -f ~/.bashrc ]; then
	. ~/.bashrc
fi

Tip

Not sure which files run? Put echo "reading ~/.bashrc" at the top of each one, then open a new terminal and log in again with su - yourname. You’ll see the exact order.

Sourcing a file: . and source#

After you edit ~/.bashrc, the change doesn’t apply to shells that are already open. You can log out and back in, or source the file:

bash
source ~/.bashrc
. ~/.bashrc

Both lines do the same thing. . is the original POSIX command and works in every Bourne-style shell. source is the Bash name for it.

Sourcing runs the file’s commands in your current shell. Running it as a program (bash ~/.bashrc or ./script.sh) starts a child process instead, and any variable, alias or cd it makes disappears when the child exits. That’s why startup files are always sourced, never executed.

Shell variables and environment variables#

A plain assignment creates a shell variable. It lives only in the current shell. No spaces around the =:

bash
GREETING="hello"
echo $GREETING
bash -c 'echo "child sees: [$GREETING]"'
console
hello
child sees: []

export turns it into an environment variable, and every program you start from now on gets a copy:

bash
export GREETING
bash -c 'echo "child sees: [$GREETING]"'
console
child sees: [hello]

You can also assign and export in one go: export EDITOR=vim. A child gets a copy, so a script that changes a variable never changes it in the shell that started it.

The tools you need for the exam:

CommandWhat it does
export VAR=valueSet a variable and put it in the environment
export -n VARKeep the variable but remove it from the environment
export -f nameExport a function so child Bash shells can use it
export -pList exported variables
envPrint the environment (exported variables only)
env VAR=value cmdRun one command with an extra or changed variable
env -i cmdRun a command with an empty environment
env -u VAR cmdRun a command without that variable
setWith no arguments: print all shell variables and functions
set -o / set +oShow shell options; set -o name turns one on, set +o name turns it off
unset VARDelete a variable
unset -f nameDelete a function

env versus set is a favorite exam trap: env shows only the environment, set shows every variable the shell knows, exported or not, plus its functions.

set also switches shell options. A few you’ll meet:

bash
set -o noclobber   # > refuses to overwrite an existing file (use >| to force)
set -x             # print each command before running it (debugging); set +x turns it off
set -u             # treat unset variables as an error
set -e             # exit a script when a command fails

To set a variable for one command only, put it in front of the command. It doesn’t stay in your shell afterwards:

bash
LANG=C date
TZ=Asia/Tokyo date

Variables worth knowing: HOME, USER, SHELL, PWD, PS1 (the prompt), HISTSIZE, EDITOR, LANG, and the most important one, PATH.

Setting the command search path#

When you type a command name without a slash, Bash looks for it in each directory of PATH, left to right, and runs the first match:

bash
echo $PATH
console
/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games

To add a directory, append or prepend to the existing value. Never overwrite it, or ls and friends stop working:

bash
export PATH="$PATH:/opt/tools/bin"     # searched last
export PATH="$HOME/bin:$PATH"          # searched first, so it can override system commands

Where to put it:

  • Just for you, every login: ~/.profile (or ~/.bash_profile if you have one). Debian and Ubuntu already add ~/bin and ~/.local/bin there if those folders exist. RHEL and Fedora add ~/.local/bin and ~/bin in ~/.bashrc.
  • For every user: a new file in /etc/profile.d/, for example /etc/profile.d/tools.sh. Editing /etc/profile also works, but package updates may replace it.

Check what Bash will actually run with type (or which for files on PATH):

bash
type ls cd ll
type -a echo
console
ls is hashed (/usr/bin/ls)
cd is a shell builtin
ll is aliased to `ls -alF'
echo is a shell builtin
echo is /usr/bin/echo

Bash remembers where it found commands (that’s “hashed”). If you move a program, hash -r clears that memory.

Warning

Never put . (the current directory) in PATH, especially for root. Anyone who can write a file called ls into a directory you cd into could make you run their code. That’s why you start local programs with ./script.sh.

Aliases#

An alias is a short name that expands into a longer command. Put them in ~/.bashrc:

bash
alias ll='ls -alF'
alias rm='rm -i'
alias gs='git status'
bash
alias          # list all aliases
alias ll       # show one
unalias gs     # remove one
\rm file.txt   # a backslash skips the alias for this one call

Aliases are simple text replacement for the first word of a command. They can’t take arguments in the middle, and Bash doesn’t expand them in scripts (non-interactive shells) unless the script runs shopt -s expand_aliases.

Functions#

When you need arguments, logic or several commands, write a function. Bash accepts two forms:

~/.bashrcbash
# POSIX form
mkcd() {
    mkdir -p "$1" && cd "$1"
}

# Bash keyword form
function backup {
    cp -a "$1" "$1.$(date +%F).bak"
}
bash
source ~/.bashrc
mkcd ~/projects/demo
pwd
backup notes.txt
ls notes.txt*
console
/home/amin/projects/demo
notes.txt  notes.txt.2026-12-01.bak

Inside a function, $1, $2 and so on are its own arguments, and $@ is all of them. A function runs in the current shell, so cd inside mkcd really moves you. Use local name=value for variables that shouldn’t leak out.

Useful commands around functions:

bash
type mkcd          # shows the function's body
declare -F         # list function names
unset -f mkcd      # remove it
export -f mkcd     # make it available in child bash shells

When a name exists as more than one thing, Bash picks in this order: alias, then shell keyword, then function, then builtin, then a program found on PATH.That’s why alias ls='ls --color=auto' works without looping forever: the alias is expanded once, and the ls inside it is looked up as a normal command.

Skeleton directories for new users#

When an administrator creates a user with a home directory, the contents of /etc/skel/ are copied into it. It’s the template for every new home, so it’s where you put default dotfiles:

bash
ls -A /etc/skel
console
.bash_logout  .bashrc  .profile

That’s Debian and Ubuntu. RHEL and Fedora ship .bash_logout, .bash_profile and .bashrc.

To give every future user an alias and a bin folder:

bash
sudo mkdir /etc/skel/bin
echo "alias ll='ls -alF'" | sudo tee -a /etc/skel/.bashrc
sudo useradd -m -s /bin/bash carol
sudo ls -A /home/carol
console
.bash_logout  .bashrc  bin  .profile

Things to know:

  • useradd -m creates the home and copies the skeleton. -k /path uses another skeleton directory. The default is the SKEL= line in /etc/default/useradd.
  • On RHEL and Fedora, useradd creates the home even without -m (CREATE_HOME yes in /etc/login.defs). On Debian and Ubuntu it doesn’t, so use -m or the friendlier adduser, which reads its skeleton from /etc/adduser.conf.
  • Files are copied once and owned by the new user. Changing /etc/skel later has no effect on existing users.

Exam checklist#

  • Login shell: /etc/profile, then the first of ~/.bash_profile, ~/.bash_login, ~/.profile. On exit: ~/.bash_logout.
  • Interactive non-login shell: /etc/bash.bashrc (Debian; /etc/bashrc on Red Hat) and ~/.bashrc. Distributions make the login file source ~/.bashrc.
  • . and source run a file in the current shell. Running a script starts a child that can’t change your shell.
  • VAR=x is a shell variable. export VAR puts it in the environment for child processes. unset VAR removes it, unset -f removes a function.
  • env lists the environment and runs commands with a changed one (env -i, env VAR=x cmd). set lists all variables and functions and toggles options (set -x, set -o noclobber).
  • Extend PATH with PATH="$PATH:/new/dir", never replace it, and never add .. System-wide: /etc/profile.d/*.sh; per user: ~/.profile or ~/.bash_profile.
  • alias name='cmd' for simple shortcuts, unalias to remove, \cmd to bypass. Aliases aren’t expanded in scripts.
  • Functions: name() { ...; } or function name { ...; }, with $1, $@ and local.
  • /etc/skel is copied into new homes by useradd -m (or adduser), only at creation time.

Byte check

0/3

Answer these 3 questions to commit this byte to your learning path.

  1. A user logs in over SSH. Their home has ~/.bash_profile, ~/.bash_login and ~/.profile. Which of the three does Bash read?
  2. You run MYDIR=/srv/data and then start a script that prints $MYDIR. It prints an empty line. What fixes it?
  3. You add a new .vimrc to /etc/skel. Who gets it?
Search posts and bytes

Optional account

Keep your progress everywhere

Everything on AminBytes is free to read, with or without an account. Sign in only if you want your commits, streak and merged topics saved, on every device.

or

We keep only your name, avatar and which bytes you finished, and you can delete it all anytime. Privacy