Aliases and Shell Functions: When to Use Each
Bash offers two ways to give a short name to something you type often. An alias is a text substitution: when you type the alias name as a command, Bash replaces it with a stored piece of text before running the line. A shell function is a small program with a name: it has its own arguments, can contain conditions, loops and several commands, and returns an exit status (lessons 88-96).
For a quick shortcut like ll for ls -l, both work. As soon as the shortcut needs arguments in the middle, a decision, or has to work inside scripts, only a function is suitable. This lesson explains how aliases work, where they behave in surprising ways, and how to decide between the two.
Defining and Using Aliases
The alias built-in defines an alias as name='text'. There must be no spaces around =, and the text is normally quoted because it contains spaces:
$ alias ll='ls -l'
$ ll
total 0
-rw-r--r-- 1 root root 0 Nov 24 03:58 a.txt
-rw-r--r-- 1 root root 0 Nov 24 03:58 b.log
$ alias ll
alias ll='ls -l'
$ type ll
ll is aliased to `ls -l'
$ alias
alias ll='ls -l'
alias NAMEshows one alias;aliasalone lists all of them in a form that can be pasted back into a shell.type NAMEtells you whether a name is an alias, a function, a built-in or a program (lesson 14).unalias NAMEremoves an alias, andunalias -aremoves all of them.
Aliases defined at the prompt last only until the shell exits. To keep them, put them in ~/.bashrc (lesson 146 covers the startup files).
How Alias Expansion Works
When Bash reads a command line, it checks the first word of each simple command. If that word is an alias name and is not quoted, Bash replaces it with the alias text and then continues to parse the line. Everything you typed after the alias name stays where it was, after the replacement text:
ll -h /etc becomes ls -l -h /etc
This is the whole mechanism. An alias cannot look at its arguments, cannot put them in the middle of the text, and cannot decide anything. It only works at the start of a command.
What Aliases Cannot Do: Arguments
A frequent attempt is to use $1 in an alias:
$ alias greet='echo Hello, $1!'
$ greet Ana
Hello, ! Ana
$1 is not "the alias's first argument". The line became echo Hello, $1! Ana. At the prompt, $1 is the interactive shell's own first positional parameter, which is empty, and Ana was simply appended at the end. A function handles arguments properly:
greet() { echo "Hello, $1!"; }
Defining that function failed, however, while the alias still existed:
$ greet() { echo "Hello, $1!"; }
bash: syntax error near unexpected token `('
$ unalias greet; greet() { echo "Hello, $1!"; }
bash: syntax error near unexpected token `('
The first word greet was replaced by the alias text, so Bash saw echo Hello, $1!() { ... }, which is not valid syntax. The second attempt failed too, even though it removes the alias first: the whole line was read and alias-expanded before unalias ran. This leads to the most important rule about aliases.
Aliases Are Expanded When a Line Is Read
Bash replaces aliases while it reads a line or a compound command, not when it runs it. A change to the alias table therefore affects only the lines read afterwards:
$ alias hi='echo hi from alias'; hi
bash: hi: command not found
$ hi
hi from alias
On the first line, hi had already been examined (and not found as an alias) when alias ran. On the next line, the alias existed and was expanded. The same rule explained the failed unalias greet; greet() ... above.
Once the alias was gone, both function forms worked. The function NAME { ... } form is also immune to an existing alias, because the word after the keyword function is not checked for aliases:
$ alias greet='echo Hello, $1!'
$ function greet { echo "Hello, $1!"; }
$ greet Ana
Hello, ! Ana
$ unalias greet
$ greet Ana
Hello, Ana!
The function was defined successfully, but as long as the alias existed, the alias won when greet was called. An alias takes precedence over a function with the same name, and both take precedence over built-ins and programs found in PATH. After unalias greet, the function ran.
Aliases in Scripts
Non-interactive shells, which run scripts, do not expand aliases by default:
# s1.sh
alias ll='ls -l'
type ll
ll demo
echo "status $?"
s1.sh: line 2: type: ll: not found
s1.sh: line 3: ll: command not found
status 127
shopt -s expand_aliases turns alias expansion on in a script:
# s2.sh
shopt -s expand_aliases
alias ll='ls -l'
ll demo
total 0
-rw-r--r-- 1 root root 0 Nov 24 03:58 a.txt
-rw-r--r-- 1 root root 0 Nov 24 03:58 b.log
Even then, the "expanded when read" rule applies, and a function body is read when the function is defined, not when it is called:
# s3.sh
shopt -s expand_aliases
f() { ll demo; } # defined before the alias exists
alias ll='ls -l'
g() { ll demo; } # defined after
echo "f:"; f
echo "g:"; g
f:
s3.sh: line 2: ll: command not found
g:
total 0
-rw-r--r-- 1 root root 0 Nov 24 03:58 a.txt
-rw-r--r-- 1 root root 0 Nov 24 03:58 b.log
Both functions were called after the alias existed, but only g had been defined after it. Because of these ordering effects, the Bash manual recommends functions instead of aliases for almost every purpose, and scripts should not rely on aliases at all.
The same effect matters in ~/.bashrc: an alias such as alias cp='cp -i' is expanded inside every function defined after it in the same interactive shell. A function that calls cp would then ask before overwriting, which may not be what the function intends. command cp avoids the alias, as the complete example below does.
Bypassing an Alias
Because only an unquoted first word is checked, any quoting skips the alias. command NAME skips aliases and functions:
$ \ll
bash: ll: command not found
$ command ll
bash: ll: command not found
Here ll existed only as an alias, so both forms found nothing. With a real program hidden behind an alias, for example alias rm='rm -i', the forms \rm file, 'rm' file and command rm file run the program without the -i.
A Trailing Space in an Alias
If the alias text ends with a space, Bash also checks the next word for an alias. The common use is:
alias sudo='sudo '
Without the trailing space, sudo ll would look for a program called ll and fail. With it, ll is expanded too, and the command becomes sudo ls -l.
Functions Do Everything Aliases Do, and More
A function can do anything an alias does: ll() { ls -l "$@"; } passes all arguments on with "$@", exactly like the alias. In addition, a function:
- places arguments anywhere:
greet() { echo "Hello, $1!"; } - validates its input and returns an exit status (lesson 90)
- contains several commands, conditions and loops
- uses local variables (lesson 92)
- works in scripts without any special option
- can be exported to child Bash processes with
export -f(lesson 88) - is read and defined once, and its body is shown by
type NAMEordeclare -f NAME
Wrapping a Command with the Same Name
To change the default behavior of a command, an alias is often written as alias ls='ls -F'. Bash does not expand an alias again inside its own replacement text, so this works. A function with the same idea calls itself instead:
$ ls() { ls -l "$@"; }
$ FUNCNEST=20; ls
bash: ls: maximum function nesting level exceeded (20)
Inside the function, ls refers to the function again, which calls itself endlessly. FUNCNEST=20 limited the depth so the test stopped with an error; without a limit, Bash keeps calling until it runs out of memory or the stack overflows. command skips functions and runs the real program:
$ ls() { command ls -l "$@"; }
$ ls
total 0
-rw-r--r-- 1 root root 0 Nov 24 03:58 a.txt
-rw-r--r-- 1 root root 0 Nov 24 03:58 b.log
$ type ls | head -3
ls is a function
ls ()
{
unset -f ls removes the function again.
Choosing Between Alias and Function
| Situation | Use |
|---|---|
a fixed abbreviation for a command with options: ll, la, gs for git status | alias (or function) |
default options for a command at the interactive prompt: grep --color=auto, cp -i | alias |
| arguments anywhere except at the end | function |
| more than one command, a condition or a loop | function |
| input validation, error messages, a meaningful exit status | function |
| anything used in a script | function |
| something needed by child processes | exported function, or a real script in PATH |
A practical rule: use an alias only for a plain abbreviation that you type at the prompt. Use a function for everything else. When a shortcut grows beyond a few lines or is useful outside your own shell, turn it into a script file in a folder on your PATH, such as ~/bin (lesson 39), so that other programs and other shells can run it too.
A Complete Example: A Personal Shortcuts File
shortcuts.bash collects aliases and functions for everyday interactive work. It is loaded by one line in ~/.bashrc:
# shortcuts.bash: personal shortcuts, loaded from ~/.bashrc with
# [[ -f ~/shortcuts.bash ]] && source ~/shortcuts.bash
# ---- Aliases: fixed text, interactive use only ----
alias ll='ls -lh'
alias la='ls -lhA'
alias ..='cd ..'
alias ...='cd ../..'
alias grep='grep --color=auto'
alias cp='cp -i' # ask before overwriting
alias mv='mv -i'
# ---- Functions: arguments, logic, several commands ----
# mkcd DIR: create DIR (with parents) and change into it
mkcd() {
(( $# == 1 )) || { echo "usage: mkcd DIR" >&2; return 2; }
mkdir -p -- "$1" && cd -- "$1"
}
# up [N]: go up N directory levels (default 1)
up() {
local n=${1:-1} path=
[[ $n =~ ^[1-9][0-9]*$ ]] || { echo "usage: up [LEVELS]" >&2; return 2; }
while (( n-- > 0 )); do path+=../; done
cd -- "$path"
}
# bak FILE...: copy each FILE to FILE.YYYYmmdd-HHMMSS.bak
bak() {
(( $# > 0 )) || { echo "usage: bak FILE..." >&2; return 2; }
local f stamp status=0
printf -v stamp '%(%Y%m%d-%H%M%S)T' -1
for f in "$@"; do
if [[ -f $f ]]; then
command cp -p -- "$f" "$f.$stamp.bak" && echo "saved $f.$stamp.bak"
else
echo "bak: $f: not a regular file" >&2; status=1
fi
done
return "$status"
}
# extract ARCHIVE: unpack common archive types into the current folder
extract() {
(( $# == 1 )) || { echo "usage: extract ARCHIVE" >&2; return 2; }
[[ -f $1 ]] || { echo "extract: $1: no such file" >&2; return 1; }
case $1 in
*.tar.gz|*.tgz) tar -xzf "$1" ;;
*.tar.xz|*.txz) tar -xJf "$1" ;;
*.tar.bz2|*.tbz2) tar -xjf "$1" ;;
*.tar) tar -xf "$1" ;;
*.zip) unzip -q "$1" ;;
*.gz) gzip -dk "$1" ;;
*) echo "extract: $1: unknown archive type" >&2; return 1 ;;
esac
}
# psg PATTERN: list processes whose command line matches PATTERN;
# status 1 when nothing matches
psg() {
(( $# == 1 )) || { echo "usage: psg PATTERN" >&2; return 2; }
ps -eo pid,user,etime,args | awk -v pat="$1" '
NR == 1 { header = $0; next }
$0 ~ pat && !/awk -v pat=/ { if (!found++) print header; print }
END { exit !found }'
}
How It Works
- The aliases are pure abbreviations or default options. None needs arguments in the middle, and all are meant for typing at the prompt.
mkcdcombines two commands, which an alias could only do for a fixed folder name.cdinside a function changes the directory of the current shell, because a function runs in the shell itself; a script could not do this, since it runs in a child process (lesson 93).upvalidates its argument with a regular expression and builds a path such as../../../in a loop.bakhandles any number of files, reports each failure, and returns status 1 if any file was missing. It usescommand cpso that thecp -ialias defined above does not make it ask questions.printf -v stamp '%(...)T' -1stores the current time in a variable without startingdate.extractchooses the right tool withcasepatterns (lesson 76). The longer patterns such as*.tar.gzcome before*.gz, becausecaseuses the first match.psgpasses the pattern toawkwith-v, keeps thepsheader in a variable, prints it only when there is at least one match, and excludes theawkcommand itself, whose command line contains the pattern.exit !foundturns "nothing found" into status 1, sopsgcan be used in conditions.- Every function prints a usage message to standard error and returns status 2 when called incorrectly, the same conventions as complete scripts (lesson 125).
Running the Complete Example
The file was copied to /home/ana/shortcuts.bash, ~/.bashrc sourced it and set a prompt showing the current folder, and an interactive Bash was started in ~/projects, which held a configuration file and two archives:
~/projects$ type ll mkcd | head -3
ll is aliased to `ls -lh'
mkcd is a function
mkcd ()
~/projects$ ll
total 12K
-rw-r--r-- 1 root root 8 Nov 24 03:58 app.conf
-rw-r--r-- 1 root root 156 Nov 24 03:58 site.tar.gz
-rw-r--r-- 1 root root 320 Nov 24 03:58 site.zip
~/projects$ bak app.conf nope.conf; echo "status $?"
saved app.conf.20261124-035851.bak
bak: nope.conf: not a regular file
status 1
~/projects$ mkcd notes/2026/nov
~/projects/notes/2026/nov$ pwd
/home/ana/projects/notes/2026/nov
~/projects/notes/2026/nov$ up 3
~/projects$ pwd
/home/ana/projects
~/projects$ extract site.tar.gz && cat src/readme.txt
hello
~/projects$ rm -r src; extract site.zip && ls src
readme.txt
~/projects$ extract app.conf; echo "status $?"
extract: app.conf: unknown archive type
status 1
~/projects$ up x; echo "status $?"
usage: up [LEVELS]
status 2
~/projects$ cp app.conf app.conf.copy; cp app.conf app.conf.copy
cp: overwrite 'app.conf.copy'? n
~/projects$ ..
~$ pwd
/home/ana
The prompt shows the effect of mkcd, up and the .. alias immediately: each changed the folder of the interactive shell itself. The second cp asked before overwriting because of the cp -i alias, while bak copied without asking.
psg was tested from a script that sourced the file and started a sleep 77 in the background:
source ~/shortcuts.bash
sleep 77 &
sleep 0.2
psg 'sleep 77'
psg 'nothing-like-this'; echo "status $?"
psg; echo "status $?"
kill $!
PID USER ELAPSED COMMAND
1351 root 00:00 sleep 77
status 1
usage: psg PATTERN
status 2
Note that the aliases in this file have no effect in that test script, because the script does not enable expand_aliases; the functions work there as they do at the prompt.