Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create bash alias with argument? [duplicate]

Tags:

bash

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.

like image 668
RanRag Avatar asked Jul 13 '12 08:07

RanRag


People also ask

Can bash alias take argument?

Bash users need to understand that alias cannot take arguments and parameters. But we can use functions to take arguments and parameters while using alias commands.

How do you pass arguments to alias command?

Aliases are like commands in that all arguments to them are passed as arguments to the program they alias. For instance, if you were to alias ls to ls -la , then typing ls foo bar would really execute ls -la foo bar on the command line.

How do I create an alias argument in Linux?

Solution 1. You can replace $@ with $1 if you only want the first argument. This creates a temporary function f , which is passed the arguments (note that f is called at the very end). The unset -f removes the function definition as the alias is executed so it doesn't hang around afterwards.


2 Answers

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 $ 
like image 140
Igor Chubin Avatar answered Nov 09 '22 06:11

Igor Chubin


Use this:

alias lsps='ps -elf | grep' 

Then you can issue this:

lsps processname 
like image 33
Ramazan Polat Avatar answered Nov 09 '22 08:11

Ramazan Polat