0

I'm using the terminal in MacOS. When I directly use the command find and fgrep to find the specified string in files, the result is normal. However when I'm trying to put my command into an alias command, the error occurs. Please view the details bellow. How can I fix this? Thanks.

(gluon) ULM:测试 Lever$ find ./ -type f -exec fgrep -l 'cylinderActor' {} \;
.//vtk_test.ipynb
.//.ipynb_checkpoints/vtk_test-checkpoint.ipynb
(gluon) ULM:测试 Lever$ alias fmy='find ./ -type f -exec fgrep -l $@ {} \;'
(gluon) ULM:测试 Lever$ fmy 'cylinderActor'
find: cylinderActor: unknown primary or operator
Lever
  • 5
  • 1
  • The $@ does not make much sense in the alias. It would access the parameters to the current shell (which likely don't exist) at the time the alias is evaluated. You can't pass parameters to an alias. – user1934428 Nov 12 '19 at 07:35
  • You can try, but it won't work - at least not in the sense like a `$1` would work for the shell. What you **can** do is to have a `alias f=foo -x`, and then calling it as `f bar`, which will result in `foo -x bar`; so this **is** kind of parameter passing, but the parameter is not passed to the alias; it is simply appended to the expanded comman. – user1934428 Nov 12 '19 at 07:56
  • I have tried to pass parameters to alias when finding files. It seems it works. I defined `alias fmy='find ./ -type f -name $@'` in the terminal, and then excute `fmy '*.mp3'`. It can list the mp3 files. – Lever Nov 12 '19 at 08:03
  • Yes, but for different reason as you believe. Since, as I said before, the $@ is expanded in the context of the caller, it refers to the parameter passed to your interactive shell, which likely are empty. Hence, there is nothing after "-name". But then everything you add after the alias name, is _appended_ to the generated command, and hence it gives you by chance the result you expected. You can see the difference by trying `alias h='echo $@ world'` and invoke it as `h hello`. You won't get _hello world_ in return. – user1934428 Nov 12 '19 at 08:07

1 Answers1

0

You could define this function:

fmy() {
  find . -type f -exec fgrep -l "$@" {} \;
}

which can be simplified by using grep's R option:

fmy() {
    fgrep -Rl $@
}
builder-7000
  • 7,131
  • 3
  • 19
  • 43
  • The former function definition works, However the latter one doesn't. A warning occurs `fgrep: warning: recursive search of stdin`. – Lever Nov 12 '19 at 08:33