Tuesday, 6 September 2016

How to create bash alias with argument?




I normally use ps -elf | grep proceesname to get a detailed description of the process named processname. I think that I have to write too much for this.




Now what i was thinking is to create a bash alias like



alias lsps='ps -elf | grep $1'


which will give the above detailed description only by using lsps processname.



So, my question is how do I create a bash alias which accepts an argument.




PS: I know I can write a shell script for the above task but I was just wondering how to do it with bash alias.


Answer



Very simple;



alias lsps='ps -elf | grep'


Command line arguments will be added automatically to the end of the alias:



lsps arg1 arg2 arg3 => converted to => ps -elf | grep arg1 arg2 arg3



That works only when you want to add arguments to the end of alias.



If you want to get arguments of the alias inside of the expanded command line you must use functions:



For example:



lsps()
{

ps -elf | grep "$1" | grep -v grep
}


Functions as well as aliases can be saved in your ~/.bashrc file )or a file that is included from it):



$ cat /tmp/.bash_aliases
lsps()
{
ps -elf | grep "$1" | grep -v grep

}

$ . /tmp/.bash_aliases
$

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...