Bash Aliases and Functions

Publish date: Jul 8, 2019
Tags: linux, command-line, terminal, bash, shell

Table of Contents

  1. Alias
  2. Functions

The reason we pack commands into functions and aliases is that we use it a lot and don’t want to write down that long keywords and commands over and over. When we use this kind of facility a common advice is often given: use it after you learned the full version of the command. It is a good advice and I use to follow it, but anyways, I can’t keep all these long commands in my mind. When you need to revisit the original command packed in an alias or function it is useful to be able to display their definitions.

Alias

The command to show an existing alias is simply the `alias` command without the assignment operator and the value.

# definition
alias ll='ls -lh'

# show definition
alias ll
ll='ls -lh'

Functions

When instead of alias you write functions, this can be a little different. You can use either use `type` to describe bash functions or `declare -f` to describe functions declared in sourced files in your `.bashrc` configuration.

foo () {
    echo "function definition";
}
type foo

Output:

foo is a function
foo ()
{
    echo "function definition"
}

File content in /tmp/function.sh

foo () {
    echo "sourced file function definition"
}

source /tmp/function.sh
declare -f foo

Ouptut:

foo ()
{
    echo "sourced file function definition"
}