Search code examples
javashellunix

Using path with spaces in Shell script


I am using shell script to call a java program. When calling passing java program I am passing -Dargument which has a path to a directory. This -D argument is read from a file. Now I am facing a issue when this path contains spaces. I tried with quote and also with escaping quotes but both dint work.

Here is my shell script code, test.sh

   D_ARG=`(tr '\r\n' ' ' < argument.dat)
  \#executing java code by passing above argument
   java ${D_ARG} TestProgram

Below is my argument file, argument.dat

  -Dargument1="/Path /To A/File"

When I set the echo on using set -x, I see the shell converting it to

  '-Dargument1="/Path' '/To' 'A/File"'

Where it adds single quotes when it encounters spaces and I get "/To" class not found exception. How to resolve this issue. Any suggestion or help will be really appreciable.


Solution

  • Try this:

    ARGS=
    
    # Do nothing if there are no spaces; if there are spaces, surround with quotes
    for arg in $(perl -pe '/ / or next; s/^/"/; s/$/"/' argument.dat); do
        ARGS="$ARGS $arg";
    done
    
    java $ARGS TestProgram
    

    This basically has the effect that each time a line has a space in it, it will surround with quotes, so -Da=b c will be turned into "-Da=b c".

    Note that "-Da=b c" is strictly equivalent to -Da="b c", or even more bizarre-looking forms of it:

    • '-Da='b\ c;
    • -D"a=b "c;
    • etc etc

    The only thing which matters is that whatever characters are input field separators are escaped. Yes, this is legal:

    alias l"l=ls"\ -l