Jack Gidney
Jack Gidney

Reputation: 63

How to 'cd' to the output of the 'find' command in terminal

Pretty much I want to cd to the output of the find command:

find ~ -name work_project_linux
cd the_output

Upvotes: 2

Views: 633

Answers (1)

John Kugelman
John Kugelman

Reputation: 361615

In general the best way to execute an arbitrary command on the results of find is with find -exec. Curly braces {} are placeholders for the file names it finds, and the entire command ends with + or \;. For example, this will run ls -l on all of the files found:

find ~ -name work_project_linux -exec ls -l {} +

It doesn't work with some special commands like cd, though. -exec runs binaries, such as those found in /usr/bin, and cd isn't a binary. It's a shell builtin, a special type of command that the shell executes directly instead of calling out to some executable on disk. For shell builtins you can use command substitution:

cd "$(find ~ -name work_project_linux)"

This wouldn't work if find finds multiple files. It's only good for a single file name. Command substitution also won't handle some unusual file names correctly, such as those with embedded newlines—unusual, but legal.

Upvotes: 4

Related Questions