I have come across this issue while trying to build up a script to do grep on multiple files for 10 different word.

The script I created, is (minified)

alias grep='grep -n'
out=`grep word $1`


some text word  
some other text word more text

The grep does work, but the alias is not being considered. It just outputs the matching lines and not the line numbers (-n is for line numbers)

and now if i run the below, it works fine

out=`grep -n word $1`

Output and the expected output from above script:

233: some text word  
532: some other text word more text

I have grep statement at many places in the script, and i don't want to go and edit each line. I am looking to override the grep once by aliasing it, but it doesn't seem to be working.

What could be the issue here? How can i make the alias work?

  • Aliases are only for interactive use (and even in this role, they should only be used in the simplest cases). They also obscure what you are actually calling: use functions (can be exported) or, in this case, keep the arguments in another variable (just like Makefiles do). – orion Apr 15 '15 at 12:17
  • Similar: stackoverflow.com/questions/32480642/… – Vadzim Sep 29 '19 at 14:27

You forgot this line:

shopt -s expand_aliases


shopt -s expand_aliases
alias grep='grep -n'
out=$(grep word "$1")
echo "$out"

The problem is that you made an alias for your actual shell. When you use backticks (or $(...)), you run a sub-shell which ignores your alias (AFAIK aliases can't be exported, so you'd have to re-define them in the sub-shell).

In your case, maybe the best approach would be to set a variable containing the command. Say:

MY_GREP="grep -n"
out=`${MY_GREP} word $1`
  • No, this is wrong. The backticks create a subshell which inherits its parent's aliases. A subshell is a replica of its parent, it is not a new, separate script. – Gilles 'SO- stop being evil' Apr 16 '15 at 23:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.