Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSX How do I have a Shell script change directory to the one the script is in?

I'm using Apple's automator to create a Shell Script. I can get it to run if I change directory specifically to where the jar file is. But what if I want to change to directory to wherever the Shell script happens to be running?

Right now I have the following, which works:

cd desktop/CommonDenom/
java -XstartOnFirstThread -jar CommonDenom.jar

I know there's a way to target whatever directory the Shell script is launched from, but I can't seem to get anything to work. Please be specific with instructions as I havent been using Automator very long. Unless someone can specify how ot writ ethe script without Automator. Thanks in advance.

like image 544
dbconfession Avatar asked Mar 09 '14 16:03

dbconfession


People also ask

How do I change the directory in a script?

To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.

How do I change the path of a bash script?

For Bash, you simply need to add the line from above, export PATH=$PATH:/place/with/the/file, to the appropriate file that will be read when your shell launches. There are a few different places where you could conceivably set the variable name: potentially in a file called ~/. bash_profile, ~/. bashrc, or ~/.

Where are shell scripts stored Mac?

Usually /usr/local/bin , unless you don't want other users to have access to them, in which case $HOME/bin .


3 Answers

A standard idiom for this in shell scripts is dirname $0. The $0 variable is the path to the script that was executed, and the dirname command takes a path and strips off the last component to leave the path to the containing directory

cd "`dirname $0`"
like image 56
Ian Roberts Avatar answered Oct 19 '22 13:10

Ian Roberts


Just wanted to weigh in here. I've seen some people with this problem. If you are JUST on OSX and making your own scripts. This will do the trick :) kind of a hack, but works like a charm.

#! /bin/bash 

sudo /Applications/XAMPP/xamppfiles/xampp startapache

open /Applications/XAMPP/htdocs
like image 20
chrisallick Avatar answered Oct 19 '22 14:10

chrisallick


#!/bin/bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
cd "${DIR}"

...the rest of your script...

Credits to Ian C. on AskDifferent: https://apple.stackexchange.com/a/179064

like image 23
jakob.j Avatar answered Oct 19 '22 14:10

jakob.j