Search posts

Bash function and alias

alias command is one of the most used command in Linux.We can use alias to create a new command or to modify existing one.
The use is very simplealias <command>="<what we want to excute>"

For example, if we want to create a new command p, that will print the working directory:alias p='pwd'Let see it in action:

[bob@localhost ~]$ alias p='pwd'
[bob@localhost ~]$ p
/home/bob

As we can see we attach the string “p” to the command pwd (print working directory), and now when the user write p and execute it, then it will run pwd.
It is important to know that alias is not recursive, so if value of the alias include the alias itself, then the alias wont run itself. This is important when we modify command (like ls for example).
So let take the following example:

So as we can see the alias “ls” is replaced to ‘ls –color=auto’, but the ls that is included in the replaced string is not continually replaced.
So if the string value of an alias include the alias, then the alias inside the string value is not replaced.
In essence alias just replace one string with anther and then execute it.
But as we have seen in the example, we can use it to create a new command (like the p command in the example), or to modify an existing command (like the modification of the ls in the above example, ls was replaced with ls –color=auto).
If we have alias of an existing command and we want to run the original command and not the alias command (for example the original ls from the example above), then we can use the backslash “\”, before the command name.
So if the ls is an alias and we want to execute the binary ls, we can:\ls
And if continue with the example above:

[bob@localhost ~]$ \ls
showusername.sh

So in this case the binary (and not the alias ls), is running.

if we want to cancel alias, we can use unalias command.
so for example:

So in the example, we created an alias ll, we run it.We then remove it with unlias ll.
And then when we tried to run ll, we got “command not found”, because we had removed the alias before the second execution.

function is anther feature of bash, and it allow us to group commands together.
the structure of a function is very simple:

function <functionName> (){
command1;
command2;
command3;
.
.
.
.
}

In order to run a function we just<functionName> .
For example we can create a function that will give us information about our Linux distribution, and kernel.
let call the function os_info.