Eiji
Is there here document and here string support in Elixir?
I have tried to write mix task or even generate escript binary file, but it looks like that none of those ways supports some useful shell input methods. I tried to inspect arguments simply with IO.inspect(args)
here-document (<< operator)
A here document is a special-purpose code block. It uses a form of I/O redirection to feed a command list to an interactive program or a command, such as ftp, cat, or the ex text editor.
Source: https://www.tldp.org/LDP/abs/html/here-docs.html
What I have tried:
# Escript example:
$ ./example --test <<EOL
line 1
line 2
line 3
EOL
["--test"]
# Mix task example:
mix example.demo --test <<EOL
line 1
line 2
line 3
EOL
["--test"]
here-string (<<< operator)
A here string can be considered as a stripped-down form of a here document .
It consists of nothing more than COMMAND <<< $WORD ,
where $WORD is expanded and fed to the stdin of COMMAND .
Source: Here Strings
What I have tried:
# Escript example:
./example --test <<< 5*4
["--test"]
# Mix task example:
mix example.demo --test <<< 5*4
["--test"]
Maybe I need to compile Erlang with some extra flags or maybe it’s just not supported at all?
Marked As Solved
alco
I see. So the question is not about Elixir at all, it’s about passing multiple lines as a single positional argument to a program when running it in a shell.
The common practice is to use quotes like NobbZ has suggested. You could use shell substitution but that would look rather weird:
$ elixir -e "IO.inspect System.argv" -- --test $(cat <<EOL
bar
baz)
EOL
)
["--test", "bar", "baz)"]
# Must use quotes around the shell substitution
$ elixir -e "IO.inspect System.argv" -- --test "$(cat <<EOL
"bar"
baz)
EOL
)"
["--test", "\"bar\"\nbaz)"]
Also Liked
NobbZ
No program will ever see << except for the shell, which then does some magic to turn it into the started programs stdin.
This is by design.
If --test option expects further data from stdin document as such in your programs manual, if it does not, then do not try to do stdin magic.
NobbZ
Heredocs/-strings are written to stdin of your application, but from the output you show, it seems as if you only inspect parsed options.
foo <<< bar is just syntactic sugar for echo bar | foo, while << is (roughly) equivalent to echo "l1\nl2\nl3\n" | foo.
NobbZ
Have you tried this:
$ ./example "multi
line"
NobbZ
Then use single quotes.
The user has to choose the appropriate quotes anyway. If they don’t use bash but eg fish the shell might behave different from your documentation/examples. Therefore it’s best to only document the meaning of the named/positional argument in an executable.
NobbZ
cat does read from stdin if no filename is provided as positional argument. It also reads from stdin if - is given as a filename.







