Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode a String to be used as shell argument

I need to use a name of file as an argument in linux shell command. The problem is, java gives me that name as it is, saving all that spaces and other characters, and thus shell complains. Is there a method to escape all those problematic characters before passing the string to shell?

like image 762
Rogach Avatar asked Mar 03 '11 22:03

Rogach


2 Answers

Had the same problem, single quotes wasn't sufficient (as already pointed out by Robert)

Solution:

import com.google.common.escape.Escaper;
import com.google.common.escape.Escapers;

public class YourFancyClass {
    public static final Escaper SHELL_ESCAPE;
    static {
        final Escapers.Builder builder = Escapers.builder();
        builder.addEscape('\'', "'\"'\"'");
        SHELL_ESCAPE = builder.build();
    }
}

Why such an awfully complex replacement? That's why.

Use case:

System.out.format("ln -f '%s' '%s'%n", 
    SHELL_ESCAPE.escape(anyOrig.toString()),
    SHELL_ESCAPE.escape(duplicate.toString()));

Works as intended:

ln -f '/home/user/Musik/mix-2012-13/aesthesys~ I Am Free, That Is Why I'"'"'m Lost..mp3' '/home/user/Musik/youtube converted/aesthesys~ I Am Free, That Is Why I'"'"'m Lost..mp3'
like image 132
Mike Gebirge Avatar answered Oct 20 '22 02:10

Mike Gebirge


How about using the Exec module from Apache Commons? It includes a commandline builder. Also be aware that if the filename is retrieved from user input, you should be very careful with executing commands with the user input as a program argument. Escaping improperly may lead to execution of additional commands (unless the commons module is used I guess).

like image 3
Friek Avatar answered Oct 20 '22 00:10

Friek