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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- How to get the return code of a shell script in lu
Adding quotes single or double around the file name is often sufficient, depending on the characters you have in the name it may not.
Had the same problem, single quotes wasn't sufficient (as already pointed out by Robert)
Solution:
Why such an awfully complex replacement? That's why.
Use case:
Works as intended:
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).
You should be able to put single quotes around the argument and avoid escaping it altogether. Will that work for you?
Old: myapp -f /bad/path/to/file
New: myapp -f '/good/path/to/file'