Search code examples
javaregexbashescaping

How to manually escape sensitive characters in a java string that will be run in a bash shell


I will receive use input in a java program as a string that will then be run on a bash shell to execute. My question is how to manually input a backslash in the string I am passing to the bash shell to escape sensitive characters?

I know that you need to change ; to \; to use the semicolon as a string inside the bash shell.

so for example what I want: user input = "input;otherinput" javaprogram -> sees the ; in the input and adds a \ to string to escape that once it is in bash shell ->output would be "input\;otherinput"

I have tried using methods like String.replaceAll("\;", "\\\\;"); or String.replaceAll(";", "\\\\;");

I understand needing to double escape \\ in regex to get a backslash literal ( if I am interpreting it correctly ) basically is using replace or replaceAll methods capable of accomplishing what I am looking for? or do I need to do something else?

Additionally if have seen org.apache.commons.text.StringEscapeUtils.escapeHtml4 for example which escapes automatically for html4 characters, But I am unsure if any of the other the other method versions (that escape things other than html4) would accomplish what I need in relation to bash shell escaping.

Any help is appreciated thank you.


Solution

  • If you simply want to replace ";" by "\;" (backslash semicolon) then just use replace, it does not need regex version replaceAll:

    System.out.println("abc;def;ghi".replace(";", "\\;"))
    // prints:
    abc\;def\;ghi