0

I am trying to make an executable script on Mac where it searches for a file and makes that the current directory (cd) and then runs some more commands. I started with

find . -type d  -name "MCsniperPY-master" -exec cd {}

And it says I need a + or a ;

  • I add a + and the cmd does nothing,
  • I add a ; and it says I need a + or ;

I am pretty new to Unix coding, so if there is a better way to do this let me know.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • Related (only difference is that cd is not an external command in this other question): https://unix.stackexchange.com/questions/447965/find-exec-cd-gives-error-find-cd-no-such-file-or-directory – Kusalananda Sep 05 '20 at 07:20

1 Answers1

4

using cd as argument of find's -exec will result in change directory inside find command, when find command exit, you are still in starting directory.

I would use

cd "$(find . -type d  -name "MCsniperPY-master" -print | head -1)"

where

  • find . -type d -name "MCsniperPY-master" -print search for all directories named "MCsniperPY-master" and print then
  • head -1 will retain the first one (you may omit if you are sure there is only one)
  • cd "$( ... )" will cd to that directory (or bring you back to $HOME dir if nothing is found)

You may wish to use $CDPATH that list a set of directory to search for when using cd

Kusalananda
  • 333,661
Archemar
  • 31,554
  • 1
    No,it does not change the directory in the find command, but only in the cd command. BTW: this find command would only work on a POSIX compliant platform, where cd exists as binary command and not e.g. on Linux where such a command is missing. – schily Sep 05 '20 at 08:30
  • @schily: do you mean external command in contrary to a shell built-in? – Arkadiusz Drabczyk Sep 05 '20 at 13:16
  • last time I use mac, I recall shell was zsh, so this might work if zsh is POSIX. I found this question : https://serverfault.com/questions/93388/is-there-any-reason-to-use-bash-over-zsh – Archemar Sep 05 '20 at 13:45
  • POSIX requires cd to exist as external command as well. Since find does not use the shell to call commands, this is not related to shells. BTW: @Archemar I do not see any relation to this question and zsh is definitely not POSIX compliant. – schily Sep 05 '20 at 14:44
  • 1
    You are a legend ty <3 – Random Guy Sep 05 '20 at 20:00