Search code examples
javabashshprocessbuildercp

Linux cp command not working from within Java ProcessBuilder


I'm trying to copy an image file and set it as background using Java ProcessBuilder to run a shell script on Ubuntu.

When running the script myself from terminal, it executes as expected with no problem.

i.e. ./changeBG.sh "jpg"

However, when running from inside Java I get output saying the process has finished, but upon checking the file manager I see that the cp never goes through and I end up with a black background when it runs the next command to change background.

Clues as to why cp isn't happening would be highly appreciated.

The script:

#!/bin/bash

mkdir -p /home/$USER/Pictures/Wallpapers

/bin/cp -rf ./images/newimage.$1 
/home/$USER/Pictures/Wallpapers/background.$1

gsettings set org.gnome.desktop.background picture-uri "file:///home/$USER/Pictures/Wallpapers/background.$1"

echo done 

Java code:

try {

                String cmd= "./changeBG.sh \"" + currentIMGext + "\"" ;
                System.out.println(cmd);
                ProcessBuilder bd = new ProcessBuilder(cmd.split(" "));

                Process ps = bd.start();
                BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
                String currentLine;

                while (true) {
                    currentLine = br.readLine();
                    if (currentLine == null) {
                        break;
                    }
                    System.out.println(currentLine);
                }

            } catch (Exception e2){
                e2.printStackTrace();
            }

Java output:

./changeBG.sh "jpg"
done

Solution

  • You are adding literal quotes as if you were a human writing commands in a shell. There's no human and no shell, so quotes don't enter into it. Just use

    ProcessBuilder bd = new ProcessBuilder("./changeBG.sh", currentIMGext);