开发者

Assign directory listing to variable in bash script over ssh

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?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜