4

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)

#!bin/bash
alias grep='grep -n'
out=`grep word $1`

Output

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

#!bin/bash
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?

2
  • 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). Commented Apr 15, 2015 at 12:17
  • Similar: stackoverflow.com/questions/32480642/… Commented Sep 29, 2019 at 14:27

2 Answers 2

3

You forgot this line:

shopt -s expand_aliases

e.g.

#!/bin/bash
shopt -s expand_aliases
alias grep='grep -n'
out=$(grep word "$1")
echo "$out"
-1

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`
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. Commented Apr 16, 2015 at 23:26

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.