talks icon indicating copy to clipboard operation
talks copied to clipboard

Shebang only works when cd'ed next to the script

Open ThinkChaos opened this issue 10 years ago • 1 comments

Paths in the shebang are relative to the PWD when running the script. That means that if you run any of the swift scripts from a directory that is not the script's one, it will fail to find the Carthage framework directory.

$ pwd
/path/to/talks/swiftsummit/2
$ ./colourful.swift
Roses are red
[...]
$ cd .. && 2/colourful.swift
2/colourful.swift:3:8: error: no such module 'PrettyColors'
import PrettyColors
       ^

I believe the only solution is to use a script to bootstrap the swift script. The bootstrapper could be written in Swift, as long as it has no dependencies.

You could either carry the bootstrapper with every Swift script:

$ cat 2/run.sh
#!/usr/bin/env bash
cd "$(dirname "$0")" # cd to the script's directory
xcrun swift -F Carthage/Build/iOS colourful.swift
$ 2/run.sh
Roses are red
[...]

Or if you are willing place it in a directory in your $PATH:

$ cat ~/bin/shwift # ~/bin is in my PATH
#!/usr/bin/env bash

# No extra framework search paths
[[ $# -eq 1 ]] && exec xcrun swift "$1"

# Script is last argument
script="${@:$#}"
script_dir="$(dirname "$script")"

# for each but the last arg
while [[ $# -gt 1 ]]; do
    args="$args -F '$script_dir/$1'"
    shift
done

# no quotes for $args: we want it to unpack the args
xcrun swift $args "$script"
$ head -n 1 2/colourful.swift
#!/usr/bin/env shwift Carthage/Build/iOS
$ 2/colourful.swift
Roses are red
[...]

Please note that the second script is just a proof of concept. You should write a real script if you plan on using this method.

ThinkChaos avatar Jul 06 '15 09:07 ThinkChaos

Alternatively you could just use Cato.

kylef avatar Jul 06 '15 17:07 kylef