Home > database >  How can I search for a directory with a pattern and change to it [duplicate]
How can I search for a directory with a pattern and change to it [duplicate]

Time:10-02

I would like to search for a directory within current directory (including sub directories) and then change directory to it

The following code is my try:

fd() {
   find . -type d -name *$1* -exec cd {} \;
}

It throws

find: ‘cd’: No such file or directory

while find actually find a directory

CodePudding user response:

find launches a new subshell when you use -exec argument, see this for more info.

So effectively the pwd is changed in the subshell and then you return to your original shell. In contrast, if you had replaced the cd with touch {}/foobar, it would create a file indeed in that directory.

So you need something like you mention in your answer

fd() {
   cd $(find . -name *$1* -type d | sed 1q)
}

which will modify the current shell with the cd

CodePudding user response:

I got the solution:

fd() {
   cd $(find . -name *$1* -type d | sed 1q)
}
  • Related