Aliases and Shell Functions: When to Use Each

Su Suriya Ravichandran Updated 06 Dec 2026
13 min read ·Lesson 144 of 205

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 NAME shows one alias; alias alone lists all of them in a form that can be pasted back into a shell.
  • type NAME tells you whether a name is an alias, a function, a built-in or a program (lesson 14).
  • unalias NAME removes an alias, and unalias -a removes 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 NAME or declare -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

SituationUse
a fixed abbreviation for a command with options: ll, la, gs for git statusalias (or function)
default options for a command at the interactive prompt: grep --color=auto, cp -ialias
arguments anywhere except at the endfunction
more than one command, a condition or a loopfunction
input validation, error messages, a meaningful exit statusfunction
anything used in a scriptfunction
something needed by child processesexported 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.
  • mkcd combines two commands, which an alias could only do for a fixed folder name. cd inside 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).
  • up validates its argument with a regular expression and builds a path such as ../../../ in a loop.
  • bak handles any number of files, reports each failure, and returns status 1 if any file was missing. It uses command cp so that the cp -i alias defined above does not make it ask questions. printf -v stamp '%(...)T' -1 stores the current time in a variable without starting date.
  • extract chooses the right tool with case patterns (lesson 76). The longer patterns such as *.tar.gz come before *.gz, because case uses the first match.
  • psg passes the pattern to awk with -v, keeps the ps header in a variable, prints it only when there is at least one match, and excludes the awk command itself, whose command line contains the pattern. exit !found turns "nothing found" into status 1, so psg can 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Aliases and Shell Functions: When to Use Each and get answers drawn from it.

Signed-in readers only.