1

I have these aliases in my ~/.bashrc

alias grep='grep --color=auto -H'
alias fgrep='fgrep --color=auto -H'
alias egrep='egrep --color=auto -H'

but they have no effect when I run find ... -exec grep ..., and I always have to provide those options manually.

Is there a way to tell find to rely on aliases in the -exec option's arguments? I'm thinking of configuration files, rather than other aliases.

Would it be unsafe in some way?

2 Answers 2

1

You can't use aliases like that. Aliases work only if they're used first in a long command sequence, the shell basically replaces the alias text with the actual command. When you enter a command, the shell first searches for an alias, then a function and so on. Command substitution/alias substitution doesn't work if you're using an alias in the middle of a command sequence.

Furthermore, the -exec flag of find, will always spawn a seperate process executing the binary, neither an alias, nor a function, that's hard coded.

1

Some shells allow aliases to be expanded anywhere in the command line - for example, zsh has the concept of a global alias, alias -g 'grep=grep --color=auto -H'

If your interactive shell is bash however, aliases are only expanded when they appear as the first word of a command, so you would need to wrap the grep call in a shell, and invoke the shell in a way that causes your ~/.bashrc file to be read, as though in an interactive shell session.

For example

find . -name '*.txt' -exec bash -ic 'for f do grep foo "$f"; done' find-bash {} +

AFAIK it's not unsafe in any way - however it has some overhead and is hardly more convenient than simply supplying the desired options to grep directly.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .