Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find file then cd to that directory in Linux

Tags:

In a shell script how would I find a file by a particular name and then navigate to that directory to do further operations on it?

From here I am going to copy the file across to another directory (but I can do that already just adding it in for context.)

like image 992
Candyfloss Avatar asked Aug 11 '10 12:08

Candyfloss


People also ask

How do I cd to a specific directory in Linux?

To change to a directory specified by a path name, type cd followed by a space and the path name (e.g., cd /usr/local/lib) and then press [Enter]. To confirm that you've switched to the directory you wanted, type pwd and press [Enter]. You'll see the path name of the current directory.


2 Answers

You can use something like:

pax[/home/pax]> cd "$(dirname "$(find / -type f -name ls | head -1)")"
pax[/usr/bin]> _

This will locate the first ls regular file then change to that directory.

In terms of what each bit does:

  • The find will start at / and search down, listing out all regular files (-type f) called ls (-name ls). There are other things you can add to find to further restrict the files you get.
  • The piping through head -1 will filter out all but the first.
  • $() is a way to take the output of a command and put it on the command line for another command.
  • dirname can take a full file specification and give you the path bit.
  • cd just changes to that directory.

If you execute each bit in sequence, you can see what happens:

pax[/home/pax]> find / -type f -name ls
/usr/bin/ls

pax[/home/pax]> find / -type f -name ls | head -1
/usr/bin/ls

pax[/home/pax]> dirname "$(find / -type f -name ls | head -1)"
/usr/bin

pax[/home/pax]> cd "$(dirname "$(find / -type f -name ls | head -1)")"

pax[/usr/bin]> _
like image 120
paxdiablo Avatar answered Sep 28 '22 16:09

paxdiablo


The following should be more safe:

cd -- "$(find / -name ls -type f -printf '%h' -quit)"

Advantages:

  • The double dash prevents the interpretation of a directory name starting with a hyphen as an option (find doesn't produce such file names, but it's not harmful and might be required for similar constructs)
  • -name check before -type check because the latter sometimes requires a stat
  • No dirname required because the %h specifier already prints the directory name
  • -quit to stop the search after the first file found, thus no head required which would cause the script to fail on directory names containing newlines
like image 14
Philipp Avatar answered Sep 26 '22 16:09

Philipp