How to specify batch (.command) file current location in Mac OS X
If you're using bash (i.e. the script starts with #!/bin/bash
), you can use $BASH_SOURCE to get the filename of the script. From that, you can get the directory it's in:
mydir="$(dirname "$BASH_SOURCE")"
...and then use that to find files relative to the script, e.g. cp "$mydir/fileInTheSameFolder" /tmp
(and please always use double-quotes around it, as I did here).
Note that this may be a relative path; for example, if the script was run from an interactive shell with ./scriptname.command
, it'll just come out as ".". This shouldn't be a problem unless the script cd's somewhere else, but if you need the full path you can use this instead:
mydir="$(cd "$(dirname "$BASH_SOURCE")" && pwd)" || {
echo "Error getting script directory" >&2
exit 1
}
Or, could just cd
to the script's directory at the beginning of the script:
cd "$(dirname "$BASH_SOURCE")" || {
echo "Error getting script directory" >&2
exit 1
}
Related videos on Youtube
ConfusedNoob
Updated on September 18, 2022Comments
-
ConfusedNoob over 1 year
I have a batch file (.command) that I double click to do work. It has dependencies on files in the same folder, but if I double click the .command file it just launches and assumes the current location is /~
How do I find/specify the location of the .command file in the script itself, so I can refer to relative assets?
-
Steven Vachon over 7 yearsThe path can't be found when directory names contain spaces.
-
Gordon Davisson over 7 years@StevenVachon It should work as long as you put double-quotes around all references to the path. That is,
ls "$mydir"
andsomecommand >>"$mydir/output.log"
will work, butls $mydir
andsomecommand >>$mydir/output.log
will fail. This is one of the reasons it's a good idea to double-quote (almost) all variable references in shell scripts. -
LCB almost 6 yearsthe $BASH_SOURCE is empty in MacOS, but having a value in Linux
-
Gordon Davisson almost 6 years@LCB Are you sure you're running the script under bash, not some other shell?
-
LCB almost 6 years@GordonDavisson I got the reason because I am using
oh-my-zsh
. and I didn't know that the line#!/bin/bash
will be ignored if I run the file withsource ./script.sh
.