Skip to content

Instantly share code, notes, and snippets.

@rob-brown
Last active April 11, 2023 08:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rob-brown/7237656 to your computer and use it in GitHub Desktop.
Save rob-brown/7237656 to your computer and use it in GitHub Desktop.
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