Monday, July 11, 2022

[SOLVED] How do I write an alias for grep -R?

Issue

I end up typing

grep -Rni pattern .

and awful lot. How do I make this into an alias like

alias gr='grep -Rni $@ .'

Running that gives:

$ gr pattern
grep: pattern: No such file or directory

Even though the alias looks fine:

$ type gr
gr is aliased to `grep -R $@ .'

It seems that the $@ and the . get swapped when it's actually executed.


Solution

make a function instead of alias. Save it in a file eg mylibrary.sh and whenever you want to use the function, source the file

eg mylibrary.sh

myfunction(){
 grep -Rni ...
}

#!/bin/bash
source mylibrary.sh
myfunction 


Answered By - ghostdog74
Answer Checked By - Katrina (WPSolving Volunteer)