Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An Elixir sigil for executing terminal commands similar to Ruby.
defmodule ExecuteSigil do
@doc """
Handles the sigil %x. Takes the given command line string, unescapes the necessary
characters and replaces interpolations, executes it, and returns the
results as a string.
## Examples
iex> %x"echo Hello \x45\x6c\x69\x78\x69\x72\x21"
"Hello Elixir!\n"
"""
defmacro sigil_x({ :<<>>, _line, [string] }, []) when is_binary(string) do
string
|> Macro.unescape_string()
|> System.cmd()
end
defmacro sigil_x({ :<<>>, line, pieces }, []) do
binary = { :<<>>, line, Macro.unescape_tokens(pieces) }
quote do: System.cmd(unquote(binary))
end
@doc """
Handles the sigil %X. Takes the given command line string, executes it, and returns the
results as a string. Does not unescape characters or replace interpolations.
## Examples
iex> %X"echo Hello \x45\x6c\x69\x78\x69\x72\x21"
"Hello x45x6cx69x78x69x72x21\n"
"""
defmacro sigil_X({ :<<>>, _line, [string] }, []) when is_binary(string) do
System.cmd(string)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.