How to execute julia code in a bash shell script itself

$ cat zzz
/usr/bin/tail +4 "$0" | julia
println("hello world from a bash script")

Dont forget to

$ chmod u+x zzz

Sample run

$ ./zzz
hello world from a bash script
Julia Version 1.2.0
Commit c6da87ff4b (2019-08-20 00:03 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin18.6.0)
  CPU: Intel(R) Core(TM) i7 CPU         870  @ 2.93GHz
  LIBM: libopenlibm
  LLVM: libLLVM-6.0.1 (ORCJIT, nehalem)
$ which julia

$ ls -l /usr/local/bin/julia
lrwxr-xr-x  1 ssiew  admin  62 23 Aug 18:42 /usr/local/bin/julia -> /Applications/

Julia will also read a script on stdin:

echo "From bash"

echo '
println("hello world from Julia")
' | julia

echo "Back in bash"

Use of the ' character will have to be escaped though.

If you want an executable script but you don’t know where your julia will be installed, there’s also this standard trick (chmod u+x test.jl):

#!/usr/bin/env julia
using InteractiveUtils
println("hello world from Julia")

Actually it seems the stdin trick is Julia acting as a (cut down) REPL so that’s probably not a lot of good.

Here is yet another scripting trick I PR’ed to the document

exec julia --color=yes --startup-file=no -e 'include(popfirst!(ARGS))' \
    "${BASH_SOURCE[0]}" "$@"

@show ARGS  # put any Julia code here
$ cat <<EOF | julia

Apparently this acts as a repl though (displaying the result of every top level expression) which might not be what you want.

There’s a trick to avoid having to escape the $ in a heredoc by quoting the marker:

$ cat <<"EOF" | julia
> msg = "Hello"
> println("$msg world")

# Output
Hello world
1 Like

Can we please sticky this thread somewhere or write up these tricks in some docs… I needed this last year at my last job really bad. Also one of the sexiest selling points of Julia to linux users is it’s Bash interop.

1 Like

Maybe in

we can have a section under “Developer Documentation” called “Julia and the Bash shell”