Wouldn't it be nice if you could easily create a simple command without having to make a script out of it? Well, there is a way. This is done using aliases.
The following are the steps to create an alias:
Type
tput clear
and press Enter. Your screen should have cleared.Now enter
alias cls="tput clear"
. Now when you runcls
it will do the same thing.Let's create some more. To show a long directory listing enter
alias la="ls -la"
. Enter'la'
to run the alias.To show a long listing with the most current files last enter
'alias lt="ls -latr"'
.
If you create an alias and then decide you no longer want it you can remove it by using the unalias
command, for example, unalias cls
.
You can also use aliases to move around the filesystem efficiently. This is very handy and will save you an incredible amount of typing. Here are some examples:
mkdir /home/jklewis/linuxbook
alias lbook="cd /home/jklewis/linuxbook"
lbook
You will now be taken to that directory. Here is something I make frequent use of on my systems:
export LBOOK="/home/jklewis/linuxbook"
alias lbook="cd $LBOOK"
lbook
As you can see, running lbook
will take you to the directory as shown above. However, you can also use the LBOOK
variable to copy files to that directory:
cd /tmp
touch f1.txt
cp f1.txt $LBOOK
The file f1.txt
will now exist in the /home/jklewis/linuxbook
directory. This becomes even more handy when extremely long filenames are used.
You can list your aliases by just running alias
without any parameters. Any time you find yourself constantly typing the same commands or filenames consider creating an alias for it.
Note that the above examples will only be effective in that terminal and will not persist across a reboot. See the next section on how to make the changes permanent.
Also, in some cases, what you want to do may be too complicated for an alias, for example, to check for the proper number of parameters. This is where you can create a shell script, which will be covered in Chapter 8, Working with Scripts.