Search code examples
bashjuliaeofheredoc

How to use the value of a variable in a heredoc function in BASH to run a julia command


I am new to BASH and to Julia, and I am trying to do the following steps:

  1. Save a filepath in a variable
  2. Use this variable in a julia command, which i managed to execute through bash by using a heredoc function

Hard-coded command that works:

cat << "EOF" | julia --project=.
module test
            ARGS=["/path/To/My/Directory"]
            include("nameOfMyProject.jl")
            end
EOF

The problem is, that I want to exchange the hardcoded path with the value of a variable. I tried:

path="/path/To/My/Directory"
cat << "EOF" | julia --project=.
module test
            ARGS=[$path]
            include("nameOfMyProject.jl")
            end
EOF

However, that does not work. I read i should try to use <<EOF instead of << "EOF" but then I receive this error: syntax: "/" is not a unary operator I am not sure how to interprete this, since it might actually access the variable and find the "/", but it does work with it if I use "/" in the hard-coded way... so why not there? I am not sure if my problem lies in the heredoc function or in something with this variable, but I would be grateful for any help!

Solution for this problem: I am adding this for reference, if someone else has the same problem. The format that does the trick nicely is:

path="/path/To/My/Directory"
julia --project=. <<EOF
module test
            ARGS=["$path"]
            include("nameOfMyProject.jl")
            end
EOF

Thanks to Jetchisel and Jens


Solution

  • From the bash manual (emphasis mine):

    Here Documents

    This type of redirection instructs the shell to read input from the current source until a line containing only delimiter (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input (or file descriptor n if n is specified) for a command.

       The format of here-documents is:
    
              [n]<<[-]word
                      here-document
              delimiter
    

    No parameter and variable expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `.

    So all you need is

    julia --project=. << EOF
    ...$FOO...
    EOF