Avner Barr Avner Barr - 1 year ago 75
Bash Question

How to get the directory path of a script in the shebang line

Currently I can run a script only from the containing directory since the shebang line includes a path relative to the current directory

#!/usr/bin/env xcrun swift -F ./Rome/ -framework Swiftline

How is it possible to modify the
to an absolute path?

to something that will work from any directory? I've tried the following:

doesn't work

dirname $0
/Rome/ doesn't work

doesn't work

Answer Source

#!/usr/bin/env xcrun swift -F ./Rome/ -framework Swiftline won't work because of the way the shebang line works. Everything after the first space on the shebang line is taken as a single argument. In this case, env will be passed "xcrun swift -F ./Rome/ -framework Swiftline" as first argument and the filename containing this shebang as second argument, which will not work since xcrun swift -F ./Rome/ -framework Swiftline is not a file.

You can see that easily by making a fake interpreter which just prints its arguments, for example a /tmp/run.sh containing:

printf "%s\n" "$@"

Then using this interpreter in a script /tmp/foo.sh:

#!/tmp/run.sh -a -b -c

When running foo.sh, you will see arguments passed to the interpreter:

-a -b -c

You will have to provide a normal shell script that runs the xcrun stuff in addition to your file. The shebang will not work for your case.