2

I have a folder structure like this:

/domains/some-domain-1/applications/j2ee-apps
/domains/some-domain-2/applications/j2ee-apps
/domains/some-domain-3/applications/j2ee-apps

What is the best way to handle folders like this where the parent and child folders are the same? For example, if I wanted to cd to a cousin dir j2ee-apps of another domain folder from is there an easy way? What if I wanted to run a ls from the top level and get everything in the bottom folders (eg: j2ee-apps)?

Does anyone have any clever advice on how best to work with this?

2 Answers2

5

For ls, one can use the following to obtain the full list:

ls /domains/*/applications/j2ee-apps

To switch from one branch to the other I fear there is no easy way to do what you want.

3

You can set a variable to hold the variant part. Like so:

domain='some-domain-1'
cd /domains/$domain/applications/j2ee-apps
domain='some-domain-2'
cd /domains/$domain/applications/j2ee-apps

Since the cd command is the same, you can recall it on your shell with the arrow keys.

Depending on how frequently you do this, you might want to define a function in your .bashrc.

cdj2(){
  cd /domains/"$1"/applications/j2ee-apps
}

Then you can cdj2 some-domain-1.

Shell globbing (aka pathname expansion) can take care of the other part (see Stéphane Gimenez's answer). The find command would be useful if the directory structures weren't exactly the same, but you still want to see all the files matching a certain name.

find /domains -name 'j2ee-apps' -exec ls {} \;

Shawn J. Goff
  • 46,081
  • What is the part on the end: '{} '? – javamonkey79 Oct 08 '11 at 01:27
  • I love the function definition suggestion, thanks! – javamonkey79 Oct 08 '11 at 01:36
  • The funny bit at the end s the way the -exec option's arguments need to be formated. {} is replaced by the filename(s depending on other args and results). The argument has to be terminated with a ;, however, the shell interprets the ; and doesn't pass it to the command unless you escape it with a \\. – Shawn J. Goff Oct 08 '11 at 01:39
  • I can't seem to get the functions to work though :( Some tutorials say to use 'function name() { ... }' but this differs from your syntax. Neither seems to work. Is there something else special that one needs to do? – javamonkey79 Oct 08 '11 at 01:46
  • When I put it in my .bash_profile using the 'function name(){...}' syntax it works. – javamonkey79 Oct 08 '11 at 01:53
  • The function part should definitely not matter. The POSIX standard specs function definitions like I've shown, and I've not seen a shell that didn't like it (there are shells that don't like the function part).

    It may be that you need to close and open your terminal or just run . ~/.bashrc (and don't forget the leading period-space).

    – Shawn J. Goff Oct 08 '11 at 02:05