-2

I have created this bash function to recursively find a file.

ff() {
    find . -type f -name '$1'
}

However, it returns no results. When I execute the command directly on the commandline, I do get results. I am not sure why it behaves differently, as shown below.

mattr@kiva-mattr:~/src/protocol$ ff *.so
mattr@kiva-mattr:~/src/protocol$ find . -type f -name '*.so' 
./identity_wallet_service/resources/libindystrgpostgres.so

Why does my function not work as expected? I am using MacOS and bash shell.

Thnx Matt

  • please explain how this is a duplicate? I know little to nothing to of the differences of ' vs " so how know to search for that question and would I find I have found a duplicate? – just_a_programmer Jul 31 '19 at 18:19
  • It is a duplicate because the linked question and the answers therein will solve your problem. It's no problem if you can't find the duplicate questions, this site is set up so that users of a certain reputation can find them for you. – jesse_b Jul 31 '19 at 18:21

2 Answers2

2

Variables don't expand inside single quotes. You need to double quote it:

ff() {
    find . -type f -name "$1"
}

You were searching for the literal string $1


Note: You should also quote your command line argument so that the * doesn't expand to the name of a file in your pwd.

ff "*.so"

See: Quoting

jesse_b
  • 37,005
2

The problem is you're using single quotes around '$1' in your definition of ff, so you're actually running find to look for a file literally named $1.

You can fix that by using double quotes instead:

ff() {
    find . -type f -name "$1"
}

You also have a problem on your call to ff, in that you're passing an unquoted *.so that will be expanded by the shell if there's a file named *.so in the current directory.

For instance, this will fail:

mattr@kiva-mattr:~/src/protocol$ touch bogusname.so
mattr@kiva-mattr:~/src/protocol$ ff *.so

It will only search for bogusname.so and will fail to find libindystrgpostgres.so.

To fix that, you should use either double or single quotes around *.so when calling the ff function:

mattr@kiva-mattr:~/src/protocol$ ff '*.so'

Or, also valid:

mattr@kiva-mattr:~/src/protocol$ ff "*.so"
filbranden
  • 21,751
  • 4
  • 63
  • 86