/** performs replacements on a string so that it can be legally inserted into a double-quoted bash context * (without the surrounding double quotes; see also {@link #wrapBash(String)}) */ public static String escapeLiteralForDoubleQuotedBash(String unquotedInputToBeEscaped) { StringBuilder out = new StringBuilder(); try { escapeLiteralForDoubleQuotedBash(unquotedInputToBeEscaped, out); } catch (IOException e) { // shouldn't happen for StringBuilder throw Throwables.propagate(e); } return out.toString(); }
/** * Merges the commands and env, into a single set of commands. Also escapes the commands as required. * * Not all ssh servers handle "env", so instead convert env into exported variables */ protected List<String> toCommandSequence(List<String> commands, Map<String,?> env) { List<String> result = new ArrayList<String>((env!=null ? env.size() : 0) + commands.size()); if (env!=null) { for (Entry<String,?> entry : env.entrySet()) { if (entry.getKey() == null || entry.getValue() == null) { LOG.warn("env key-values must not be null; ignoring: key="+entry.getKey()+"; value="+entry.getValue()); continue; } String escapedVal = BashStringEscapes.escapeLiteralForDoubleQuotedBash(entry.getValue().toString()); result.add("export "+entry.getKey()+"=\""+escapedVal+"\""); } } for (CharSequence cmd : commands) { // objects in commands can be groovy GString so can't treat as String here result.add(cmd.toString()); } return result; }
/** transforms e.g. [ "-Dname=Bob Johnson", "-Dnet.worth=$100" ] to * a java string "\"-Dname=Bob Johnson\" \"-Dnet.worth=\$100\"" -- * which can be inserted into a bash command where it will be picked up as 2 params */ public static String doubleQuoteLiteralsForBash(String... args) { StringBuilder result = new StringBuilder(); for (String arg: args) { if (!Strings.isEmpty(result)) result.append(" "); result.append("\""); result.append(escapeLiteralForDoubleQuotedBash(arg)); result.append("\""); } return result.toString(); }
/** @see #wrapBash(String) */ public static void wrapBash(String value, Appendable out) throws IOException { out.append('"'); escapeLiteralForDoubleQuotedBash(value, out); out.append('"'); }