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
CodeMoose
  • 247

1 Answers1

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.