0

I would like a command like

    cd ./test/zen/

but working with the name of a file in it, like that

command ./test/zen/rename.sh

and go in /test/zen

There is a way? I can't really use pipe cause I need it for a line like

find -name "rename.sh" -exec sh {} \;

Or there is a solution to execute with this last command a script in the directory where he stand and not in directory where I execute my last command...

Any ideas? Thanks ^_^

A D
  • 25
  • 4
  • Could you be a little more explicit about the use case? It sounds like all you *really* need is to change from `-exec` to `-execdir`. (Also, needing something to work when called from `find` is a critical detail, since there's extra work needed to make a shell function available to a newly-started shell, such as those `-exec sh` invokes). – Charles Duffy Sep 16 '18 at 21:08
  • It's difficult to follow what you're asking for, but perhaps you're trying to determine the directory the script lives in, and `cd` to that directory? [This question](https://stackoverflow.com/q/59895/113632) covers this. – dimo414 Sep 16 '18 at 21:12
  • @CharlesDuffy Thanks, I didn't know execdir, it's perfect. – A D Sep 16 '18 at 21:39

2 Answers2

0

You can use a function for that purpose:

cdf() {
    cd $(dirname $1)
}

There is missing the error control, parameter checking and so on, but you get the idea.

Poshi
  • 4,499
  • 3
  • 12
  • 27
  • Needs more quotes to work with names with spaces, and an end-of-options sigil to work with directory names that start with dashes. Consider running your answers through http://shellcheck.net/ – Charles Duffy Sep 16 '18 at 21:03
  • ...to be a bit more specific, this should be `cdf() { cd -- "$(dirname -- "$1")"; }`. After adding those missing quotes, an error from `dirname` will be correctly propagated back to `cd`, because `cd ""` isn't a valid command (unlike `cd` alone, which is). – Charles Duffy Sep 16 '18 at 21:04
  • Re: the `--`s, see Guideline 10 in http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02 – Charles Duffy Sep 16 '18 at 21:06
0

Find already supports it:

find /var -mount -name "ba*" -execdir pwd \;

from man find:

   -execdir command {} +
          Like  -exec, but the specified command is run from the subdirec‐
          tory containing the matched file, which is not normally the  di‐
          rectory in which you started find.  As with -exec, the {} should
          be quoted if find is being invoked from a shell.
Charles Duffy
  • 235,655
  • 34
  • 305
  • 356
Ipor Sircer
  • 2,939
  • 3
  • 7
  • 14