Shell aliases make it easier to use commands by letting you establish abbreviated command names and by letting you prespecify common options and arguments for a command. To establish a command alias, issue a command of the form:
alias
name
='command
'
where command
specifies the command for which
you want to create an alias and name
specifies
the name of the alias. For example, suppose you frequently type the
MS-DOS command dir when you intend
to type the Linux command ls -l. You
can establish an alias for the ls -l
command by issuing this command:
alias dir='ls -l'
Once the alias is established, if you mistakenly type dir, you’ll get the directory listing you wanted instead of the default output of the dir command, which resembles ls rather than ls -l. If you like, you can establish similar aliases for other commands.
Your default Linux configuration probably defines several aliases on your behalf. To see what they are, issue the command:
alias
If
you’re logged in as root
, you may see the
following aliases:
alias cp='cp -i'
alias dir='ls -l'
alias ls='ls --color'
alias mv='mv -i'
alias rm='rm -i'
Notice how several commands are
self-aliased. For example, the command rm -i
is aliased as rm. The
effect is that the -i option appears
whenever you issue the rm command,
whether or not you type the option. The -i option specifies that the shell will prompt
for confirmation before deleting files. This helps avoid accidental
deletion of files, which can be particularly hazardous when
you’re logged in as root
. The alias
ensures that you’re prompted for confirmation even if you
don’t ask to be prompted. If you don’t want to be
prompted, you can issue a command like:
rm -f
files
where files
specifies the files to be deleted.
The -f option has an effect opposite
that of the -i option; it forces
deletion of files without prompting for confirmation. Because the
command is aliased, the command actually executed is:
rm -i -f
files
The -f option takes precedence over the -i option, because it occurs later in the command line.
If you want to remove a command alias, you can issue the unalias command:
unalias
alias
where alias
specifies the alias you want to
remove. Aliases last only for the duration of a login session, so you
needn’t bother to remove them before logging off. If you want
an alias to be effective each time you log in, you can use a shell
script, which we’ll discuss later in the chapter.