I am trying to make an executable script on Mac where it makes the directory it is housed in the current directory (cd) and then runs some more commands. I started with a find command however in the end that ended up causing issues because of similarly named files. Thanks in advance!

I don't know what code to run however it will include the cd command.

What I expect to happen is that by running a few commands I can then create files in the folder the executable is housed in.

  • You don't have enough information. Edit your question and add the directory structure, the code that you are running, and the expected result that you are looking for. – Nasir Riley Nov 16 '20 at 7:25

You can extract the path to the directory containing the script from the name of the script. The name of the script is stored in $0 variable. You can use dirname to extract path from it. So, to change the current working directory to the location of the script when it is run, you could start it like this:

cd "$(dirname "$0")"

I've quoted $0 before passing to dirname as well as the substitution $(…) before passing to cd in case the path contains spaces.

  • 1
    Need to quote the argument to cd in case the path has spaces (more likely on macOS). If you care about not executing external commands, cd "${0%/*}" where the string manipulation strips the shortest glob pattern /* from the end of $0. – Rich Nov 16 '20 at 17:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.