How to execute julia code in a bash shell script itself

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

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
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-6.0.1 (ORCJIT, nehalem)
$ which julia
/usr/local/bin/julia

$ ls -l /usr/local/bin/julia
lrwxr-xr-x  1 ssiew  admin  62 23 Aug 18:42 /usr/local/bin/julia -> /Applications/Julia-1.2.app/Contents/Resources/julia/bin/julia

Julia will also read a script on stdin:

#!/bin/bash
echo "From bash"

echo '
println("hello world from Julia")
versioninfo()
' | 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")
versioninfo()

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 https://docs.julialang.org/en/latest/manual/faq/#man-scripting-1

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

@show ARGS  # put any Julia code here
5 Likes
$ cat <<EOF | julia
versioninfo()
EOF

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")
> EOF

# Output
"Hello"
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 https://docs.julialang.org/en/v1/manual/documentation/index.html

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

2 Likes