Avner Barr Avner Barr - 5 months ago 24
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?

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

$0/Rome/
doesn't work

dirname $0
/Rome/ doesn't work

$1/Rome/
doesn't work

Answer

#!/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:

#!/bin/sh
printf "%s\n" "$@"

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

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

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

-a -b -c
./foo.sh

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.