28

I have a Java program Desktop/testfolder/xyz.jar on a remote machine. It has a configuration file on the same folder. When I SSH into the machine, I do:

"ssh user@remote java -cp Desktop/testfolder/xyz.jar Main"

The problem here is the configuration file is not in the path, as we are in the home folder so my program cannot read the configuration.

I want to first go into that folder and then run the program from that folder. In a shell script if I did this

"ssh user@remote cd Desktop/testfolder"
"java -cp xyz.jar Main"

it executes the first statement and when the second statement is run it runs on my current machine not the remote machine.

Can we do only one command or there are any other solutions for this?

1

3 Answers 3

44

Try something like this:

ssh [email protected] "cd /home && ls -l"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks both of your comments helped !
You're welcome! Trey's and my answer do the same thing provided the first part of the command "works" - the version with the && doesn't perform the second part of the command if the first part fails. For example, compare ssh [email protected] "cd /non-existant ; ls -l" to ssh [email protected] "cd /non-existant && ls -l". In the first case you still get some output from the ls -l command (even though the cd failed - probably the home dir of the you user) and in the latter case the ls -l command is skipped because the first operand returned false.
18

You could try separating the commands by a semicolon:

ssh user@remote "cd Desktop/testfolder ; java -cp xyz.jar Main"

3 Comments

It is important to note the difference between these two operators: && and ;. && Means that the second command will execute if, and only if the first command executes and returns with an exit status of zero (no errors) while ; allows the following command to execute regardless of it's exit status.
It is also worth noting that a newline is permitted in the string where you have a semicolon. (Yes, regular strings can span multiple lines in sh and derivatives, without any additional syntax at all.)
...to be a little more explicit about the relevance of the prior comment here -- using ; instead of && means that the java interpreter can be invoked in the wrong directory if the cd fails, whereas ; will prevent that. Using && is thus more correct.
6

If you want to split your commands over multiple lines for the sake of readability, you could also pass the list of commands to the bash command as follows:

ssh [email protected] bash -c "'
  cd Desktop/testfolder
  java -cp xyz.jar Main
'"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.