...
/Creating Shortcuts with Aliases and Functions
Creating Shortcuts with Aliases and Functions
Learn how to create commands using aliases and functions.
We'll cover the following...
Bash allows us to define our own versions of commands, either through aliases or through functions. Aliases let us create shortcuts for commands or override the default options for existing commands. We define them with the alias
command, but it’s better to define them in our ~/.bashrc
file. Let’s define some aliases.
Aliases
Let’s create an alias for ls -alh
so we can avoid typing it out. We add this line to the end of the ~/.bashrc
file to define an alias called ll
:
alias ll='ls -alh'
We then source the file to apply the changes:
$ source ~/.bashrc
Now, we try running the ll
alias:
$ ll
Run the complete code on the terminal below for practice.
cat << "EOF" > /.bashrc
# START:return
[ -z "$PS1" ] && return
# END:return
# START:histcontrol
HISTCONTROL=ignoreboth
# END:histcontrol
# START:histappend
shopt -s histappend
# END:histappend
# START:histsize
HISTSIZE=1000
HISTFILESIZE=2000
# END:histsize
# START:histignore
HISTIGNORE="exit:clear"
# END:histignore
# START:editor
export EDITOR=nano
export VISUAL=nano
# END:editor
# START:path
export PATH="~/bin:$PATH"
# END:path
# START:colorprompt
USERCOLOR='\[$(tput setaf 6)\]' # cyan
RESET='\[$(tput sgr0)\]'
PS1="${USERCOLOR}\u${RESET}@\h:\w \\$ "
# END:colorprompt
# START:alias_ll
alias ll='ls -alh'
# END:alias_ll
EOF
source /.bashrc
ll
We can use this any time we want a long listing.
We can make an alias for any command we’d like. Let’s add an alias to display our public IP address quickly. We add this alias to the file that fetches our public IP address from an external website:
alias myip='curl icanhazip.com'
We’ll learn how this command works in Making Web Requests with cURL.
We save the file and then source the file to apply the changes to the current shell:
$ source ~/.bashrc
You can run the complete code on the terminal below for practice.
cat << "EOF" > /.bashrc
# START:return
[ -z "$PS1" ] && return
# END:return
# START:histcontrol
HISTCONTROL=ignoreboth
# END:histcontrol
# START:histappend
shopt -s histappend
# END:histappend
# START:histsize
HISTSIZE=1000
HISTFILESIZE=2000
# END:histsize
# START:histignore
HISTIGNORE="exit:clear"
#
...