During this short tutorial we are going to create a command of our own using the alias command. But before we start, we need to reveal a small command line trick. It's possible to put more than one command on a line by separating each command with a semicolon character. It works like this:
command1; command2; command3...
Here's the example we will use:
[me@linuxbox ~]$ cd /usr; ls; cd - bin games kerberos lib64 local share tmp etc include lib libexec sbin src /home/me [me@linuxbox ~]$
As we can see, we have combined three commands on one line. First we change directory to /usr then list the directory and finally return to the original directory (by using 'cd -') so we end up where we started. Now let's turn this sequence into a new command using alias. The first thing we have to do is dream up a name for our new command. Let's try “test”. Before we do that, it would be a good idea to find out if the name “test” is already being used. To find out, we can use the type command again:
[me@linuxbox ~]$ type test test is a shell builtin
Oops! The name “test” is already taken. Let's try “foo”:
[me@linuxbox ~]$ type foo bash: type: foo: not found
Great! “foo” is not taken. So let's create our alias:
[me@linuxbox ~]$ alias foo='cd /usr; ls; cd -'
Notice the structure of this command:
After the command “alias” we give alias a name followed immediately (no whitespace allowed) by an equals sign, followed immediately by a quoted string containing the meaning to be assigned to the name. After we define our alias, it can be used anywhere the shell would expect a command. Let's try it:
[me@linuxbox ~]$ foo bin games kerberos lib64 local share tmp etc include lib libexec sbin src /home/me [me@linuxbox ~]$
We can also use the type command again to see our alias:
[me@linuxbox ~]$ type foo foo is aliased to `cd /usr; ls ; cd -'
To remove an alias, the unalias command is used, like so:
[me@linuxbox ~]$ unalias foo [me@linuxbox ~]$ type foo bash: type: foo: not found
While we purposefully avoided naming our alias with an existing command name, it is not uncommon to do so. This is often done to apply a commonly desired option to each invocation of a common command. For instance, we saw earlier how the ls command is often aliased to add color support:
[me@linuxbox ~]$ type ls ls is aliased to `ls --color=tty'
To see all the aliases defined in the environment, use the alias command without arguments. Here are some of the aliases defined by default on a Fedora system. Try and figure out what they all do:
[me@linuxbox ~]$ alias alias l.='ls -d .* --color=tty' alias ll='ls -l --color=tty' alias ls='ls --color=tty'
There is one tiny problem with defining aliases on the command line. They vanish when your shell session ends. To retain them, you'll need to define them in your startup shell script. (This could be your .bashrc file if this is the one that you use.)
Published on Wed 08 April 2009 by Larry Epson in Linux with tag(s): alias linux