def _escape_arg(arg):
    """Put quotes around the input string, escaping slashes and quotes within."""

    # A little bit of a hack: don't escape arguments that splice in another
    # shell command "$(...)".
    if arg.startswith("$(") and arg.endswith(")"):
        return arg

    # Escape backslashes.  However, in the pattern "\$", leave it as-is so that we can
    # emit "$" without the shell evaluating them.  For example: "-rpath=\$EXEC_ORIGIN/..."
    return "\"" + arg.replace("\\", "\\\\").replace("\\\\$", "\\$").replace("\"", "\\\"") + "\""