Shortening or Changing Command Names

Problem

You’d like to shorten a long or complex command you use often, or you’d like to rename a command you can’t remember or find awkward to type.

Solution

Do not manually rename or move executable files, as many aspects of Unix and Linux depend on certain commands existing in certain places; instead, you should use aliases, functions, and possibly symbolic links.

According to the bash Reference, “Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains a list of aliases that may be set and unset with the alias and unalias built-in commands.” This means that you can rename commands, or create a macro, by listing many commands in one alias. For example, alias copy='cp' or alias ll.='ls -ld .*'.

Aliases are only expanded once, so you can change how a command works, as with alias ls='ls -F', without going into an endless loop. In most cases only the first word of the command line is checked for alias expansion, and aliases are strictly text substitutions; they cannot use arguments to themselves. In other words, you can’t do alias='mkdir $1 && cd $1' because that doesn’t work.

Functions are used in two different ways. First, they can be sourced into your interactive shell, where they become, in effect, shell scripts that are always held in memory. They are usually small, and are very fast since they are already in memory and are executed in the current process, not in a spawned subshell. ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.