3

I'm setting up a project template for my office that uses .command files to encapsulate some command-line functions, since not everyone in the office is terminal-savvy. Mostly this is going to involve some path-changing within the project, and launching some compilers/watchers like compass or grunt.

Here's the problem I'm running into - with each project having it's own svn repo, the path to any given project root is going to be different for each user:

  • Bob: /Users/bobsmith/work/clients/client-a/project-a
  • Jane: /Users/janedoe/web/projects/project-a

I want to put .command files inside a project that are capable of finding the project root, regardless of where the project is located within the system. Is there any way to accomplish this? Maybe by referencing the path of the .command being executed? Here's a sample .command that's already in place:

# Replace this path with your project directory - remember to ignore it in svn!
cd /Users/janedoe/web/projects/project-a
grunt watch
2
  • If there's only one project per user, you can set an environment variable in the user's plist which points to the project, otherwise you can use a wish prompt every time the program loads, asking which project the user wants to mess with. Jun 16, 2014 at 20:02
  • Oh, wait... the .command is already in the project... Then you can just use cd "$(dirname "$0")", which will cd into the directory in which the command file is kept. Or, at least, that's the bash way to do it. Jun 16, 2014 at 20:05

1 Answer 1

4
# This will cd into the directory in which the .command file exists
cd "$(dirname "$0")"

On the other hand...

#  This will define an environment variable that contains the full absolute path 
#+ to the directory in which the .command file is kept, and then will cd into 
#+ that directory
ABSPATH="$(cd "$(dirname "$0")" && pwd)"
cd "$ABSPATH"

Why all the double quotes?

Without them, things break when the user has spaces in the path to the project. Also- probably obvious- but this will also break if the user can't cd into the directory of their project.

Why $( ... ) rather than ` ... ` ?

That first syntax is newer, and preferred over the second one. Besides which, it's easier to see. If you think matching parens is annoying, try matching backticks- especially when there are normal single quotes interspersed between them. Both of these do the same thing; fork a subshell and run their internal command within that subshell.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .