How to make .command file execute at its location

command lineterminal

When you execute a .command file it is not at the location where the file resides. You can place a .command file anywhere with the command pwd in it, and it will always print your Users folder.

I need the file to execute at its location because I am trying to run nodemon my/file.js and currently it is looking for Users/(myname)/my/file.js which is wrong.

Best Answer

You can always used the $0 variable to find the directory the command is in and go there first.

#!/bin/bash

# Change directory to be where the command is.
cd "$(cd "$(dirname "$0")" > /dev/null && pwd)"

# Print the working directory for example.
pwd