Bash – locally created alias not being used if called using backticks (`)

aliasbashshell-script

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?

Best Answer

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"
Related Question