I want to find a file and then enter the directory containing it. I tried
find /media/storage -name "Fedora" | xargs cd but of course, I the
is not a directory error.
How do I enter its parent directory with a one line command?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
At least if you have GNU
find, you can use
-printf '%h' to get the directory
%h Leading directories of file's name (all but the last ele‐ ment). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to ".".
So you could probably do
cd "$(find /media/storage -name "Fedora" -printf '%h' -quit)"
-quit should prevent multiple arguments to
cd in the case more than one file matches.
Similar to steeldriver's solution but using
-execdir (if your
find supports it, like GNU's or FreeBSD's
find) in combination with
cd "$(find /media/storage -name "Fedora" -execdir pwd \; -quit)"
-quit is optional in case only there is only a single result and crawling the whole directory there is of no issue. On NetBSD it's
-exit and on OpenBSD it does not exist.
You can make find run a new shell in the directory it finds.
exec find /media/storage -name "Fedora" -execdir "$SHELL" \;
, after which the current directory will be the one which has a file named Fedora in it. ;)
Obviously this only does something resembling what you want if you are typing commands interactively.
cd into the first (in alphabetical order) directory that contains a file called
**: any level of directories (hidden dirs are omitted by default, use the
Dglob qualifier to include them)
: only the first
:h: head modifier: take the dirname.
cd "$(find ...)", it also works if the directory name ends in a newline character. Another advantage is that you'd get a no match error message when there's no matching directory (while in most shells
cd "" would do nothing silently).
A drawback is that it would crawl the whole of
/media/storage before returning.
There as already many answers showing how to work around the problem, and how to get something that works. However none say why it did not work in the first place.
xargs cd, can not work.
It is the same problem as writing a script to change directory.
xargsstarts a new process / the script runs in a new process.
cdchanges the current working directory of this new process.
Thus the present working directory of a process that no longer exists has been changed.
Then your call
cd in the shell, it uses a built in command. It does not create a new process. So the current working directory of the shell process is changed.
See other answers for what to do.