Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Command: What's the difference between a variable and an alias?

I'm new to linux and starting from the basics.

-- I thought alias is used to make a shortcut to a command. But I tried the following using a variable (in Ubuntu) and still works!

$ foo="mkdir Directory"
$ $foo #this will create a directory named Directory

using alias:

$ alias bar="mkdir Directory"
$ bar #creates a Directory named directory

Is that how it is supposed to work? Many thanks for the answers :)

like image 651
Rei Avatar asked Sep 08 '11 03:09

Rei


People also ask

Is an alias a variable?

An alias occurs when different variables point directly or indirectly to a single area of storage.

What does alias do in bash?

Bash aliases allow you to set a memorable shortcut command for a longer command. Bash aliases are essentially shortcuts that can save you from having to remember long commands and eliminate a great deal of typing when you are working on the command line.

Is an alias considered a variable Linux?

No, an assignment of a value to a variable is not the same as creating an alias. Creating an alias is not an assignment from the point of view of the shell.

What is the difference between an alias and a function?

Functions can be used in scripts or in the console, but are more often used in scripts. Contrary to aliases, which are just replaced by their value, a function will be interpreted by the bash shell. Functions are much more powerful than aliases. They can be used to build very complex programs.


1 Answers

Variables are much more versatile than aliases. Variables can be used anywhere in a command line (e.g. as parts of program arguments), whereas aliases can only be used as the names of programs to run, i.e. as the first word in a command line. For example:

foo="mkdir Directory"
echo $foo  # Prints "mkdir Directory"

alias bar="mkdir Directory"
echo bar  # Nothing gets expanded -- just "bar" is printed

Variables can also be exported into the environment of child processes. If you use the export builtin to export variables, then programs can use getenv(3) function to get the variables' values.

See the Bash manual for a full description of all of the different types of expansions it can perform and how it performs them. See also the section on aliases.

like image 145
Adam Rosenfield Avatar answered Oct 12 '22 02:10

Adam Rosenfield