Aliases and shell functions in rc files

Beginner · 10 min

Shorten repeated commands with aliases, use functions when you need arguments, and put both in an rc file. Includes where aliases silently do not work.

Before thisStartup files and login vs interactive shellsFunctions, arguments and scopeHistory and readline shortcuts

Brodie Robertson · 10 min

Aliases and shell functions in rc files

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Brodie RobertsonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An alias is a text substitution on the first word of a command, so alias ll='ls -lh' turns ll into ls -lh before Bash parses the line.
  • An alias cannot take arguments in the middle of its text, and anything you type after it is just appended. When you need $1, write a function instead.
  • Aliases and functions defined in a terminal vanish when it closes. Put them in your interactive rc file (~/.bashrc, or a file your ~/.bash_profile sources on macOS).
  • Aliases are expanded in interactive shells only. A script that uses one gets 'command not found', so scripts should call the real command or define a function.
  • type -a name shows everything that name could mean, and \name or command name skips an alias.

The itch

Some commands you type forty times a day: git status -sb, ls -lh, cd ... The cure is to teach the shell a shorter name. Bash gives you two mechanisms and they differ in how much they understand.

I tested everything here in an interactive Bash 5.3 on macOS, loading a small file called myrc with source ./myrc so none of my real startup files were touched.

# myrc
alias ll='ls -lh'
alias gs='git status -sb'
alias ..='cd ..'
mkcd() {
  mkdir -p -- "$1" && cd -- "$1"
}

Aliases are text substitution

An alias replaces the first word of a command with a string. That is all. Bash performs the swap before it parses the line, so it works for anything that starts a command.

$ type ll
ll is aliased to `ls -lh'
$ ll myrc
-rw-r--r--@ 1 me       wheel   153B Nov 23 02:45 myrc

Anything after the alias is appended, which is why ll myrc works. alias with no arguments lists them, unalias name removes one.

That text-swap nature is also the limit. I defined alias echo-it='echo $1' and ran it after set -- POSITIONAL:

$ echo-it hello
POSITIONAL hello

The $1 was not an argument of the alias. It was the shell’s own $1, expanded when the alias was used, and hello was simply tacked on. The alias never sees its arguments.

Functions take arguments

For anything that needs the argument in the middle, or twice, or needs more than one command, use a function:

$ type mkcd
mkcd is a function
mkcd ()
{
    mkdir -p -- "$1" && cd -- "$1"
}
$ mkcd newdir/sub && pwd
.../al/newdir/sub

It runs in your current shell, which is why the cd stuck. A script could not do that, because a script runs in a child process. That is the reason mkcd is a function and not a file on your PATH.

Rule of thumb: an alias for a fixed prefix (ls -lh), a function for everything else.

Who wins

type -a lists every meaning a name has. I shadowed ls to see:

$ alias ls='echo shadowed'
$ ls myrc
shadowed myrc
$ \ls myrc
myrc
$ command ls myrc
myrc
$ type -a ls
ls is aliased to `echo shadowed'
ls is /bin/ls

Order of lookup is alias, then function, then builtin, then a file found through PATH. A backslash or command skips the alias. Both are useful when you alias a command to itself with flags, such as alias grep='grep --color=auto', and still want the plain one.

A gotcha: with an alias named hi defined, my attempt to define a function hi failed on the spot.

$ alias hi='echo alias-hi'
$ hi() { echo function-hi; }
bash: syntax error near unexpected token `('

The alias expanded the first word of the definition, turning it into nonsense. unalias hi first. Mixing the two under one name is a good way to spend a morning confused.

Scripts do not see your aliases

Aliases are expanded only in interactive shells. I wrote a script that defines alias hi=... and then calls hi, and another that sources myrc and asks about ll:

$ bash ./script.sh
./script.sh: line 3: hi: command not found
$ bash ./script2.sh
./script2.sh: line 3: type: ll: not found
mkcd is a function
expand_aliases      	off

The function from myrc arrived. The alias did not, because shopt expand_aliases is off outside an interactive shell. You can turn it on with shopt -s expand_aliases, but that is a sign you wanted a function.

This is also why scripts should not lean on your personal aliases: a script that works on your machine because of an alias breaks on everyone else’s.

Making them stick

Anything typed in a terminal disappears when it closes. The rc file is where they live. For an interactive non-login shell that is ~/.bashrc. A terminal that starts a login shell, which is the macOS Terminal default, reads ~/.bash_profile instead, so the usual arrangement is a one-line [ -f ~/.bashrc ] && . ~/.bashrc in the profile. The startup files lesson covers why. I did not edit those files on the machine I used, so I tested with source instead. After editing, run source ~/.bashrc to load changes into the current terminal.

Long rc files get hard to maintain, and dotfiles management is where that goes.

About the video

“When Should You Use Bash Aliases VS Functions VS Scripts” is a 9-minute 47-second video from Brodie Robertson, published October 2019. From the description it compares aliases, functions and scripts and the situations that suit each. It has no chapters and I could not read a transcript, so I do not know which examples it uses. It is an English-language channel, and it is older than the rest of this roadmap, though the three mechanisms have not changed. somedaysoon’s video of alias and function examples from a real .bashrc is linked as a second view.

Where this fits

Your shell now remembers commands and shortens them. Next is what it shows before each command: customizing the prompt.

Check yourself

  1. 01You want mkcd dir to create a directory and cd into it. Alias or function, and why?

    A function. It needs the argument twice, and an alias would only append whatever you typed to the end of its text.

  2. 02You alias ls to something and then need the original behaviour once. How?

    Type \ls or command ls, which skip alias lookup. Or use the full path, /bin/ls.

  3. 03A script you wrote runs your ll alias fine when typed but fails with 'command not found' as a script. Why?

    Alias expansion is off in non-interactive shells. In the script, call ls -lh directly or define a function.

  4. 04You added the alias to ~/.bashrc, opened a new terminal and nothing happened. What is a likely cause?

    The terminal started a login shell, which reads ~/.bash_profile and not ~/.bashrc. Source ~/.bashrc from ~/.bash_profile, as covered in the startup files lesson.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark