0

I'm trying to ssh into a remote machine, obtain a directory listing, assign it to a variable, and then I want to be able to use that variable in the rest of the script on the local machine.

After some research and setting up all the right keys and such, I can run commands via ssh just fine. Specifically, if I do:

ssh -t user@server "ls /dir1/dir2/; exit; bash"

I do get a directory listing. If I instead do:

ssh -t user@server "set var1=`ls /dir1/dir2/`; exit; bash"

instead gives an ls error that the directory was not found. Also of note is that this happens before I am asked for the ssh key passphrase, which makes me think that it's executing locally somehow.

Any idea on how I can create a local variable with a directory listing list of the remote host in a bash script?

1
  • Do you want that variable set on your local machine or on the remote server? Commented Oct 5, 2011 at 22:26

2 Answers 2

4

Simply

var1=( $(ssh user@server ls /dir1/dir2) )

then test it:

for line in "${var1[@]}"; do echo "$line"; done

That said, I'd prefer

ssh user@server find /dir1/dir2 -maxdepth 1 -print0 | 
    xargs -0

This will

  • deal a lot better with special filenames
  • be more flexible (man find(1))
  • adding -type f to limit to files only
Sign up to request clarification or add additional context in comments.

2 Comments

@l0b0: congrats with your 2^11 reputation !
In order to show only subdirs, i had to add a -mindepth 1 to that find :)
0

Your command in quote is executed before executing the ssh command. Escaping the single quote should fix

1 Comment

Just to be clear, that's one of these `, not one of these '. I did try escaping it with a \ (if that's even how you do it, I'm pretty new to this) but that didn't fix it, though I can't remember the error. The reason I put it there is because someone once told me I need it to make stuff into lists to loop through :) .

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.