通过 ssh 将目录列表分配给 bash 脚本中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7668423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assign directory listing to variable in bash script over ssh
提问by CHP
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.
我正在尝试通过 ssh 连接到远程机器,获取目录列表,将其分配给一个变量,然后我希望能够在本地机器上的脚本的其余部分中使用该变量。
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 运行命令就好了。具体来说,如果我这样做:
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.
而是给出一个 ls 错误,指出找不到目录。另外值得注意的是,这发生在我被要求提供 ssh 密钥密码之前,这让我认为它以某种方式在本地执行。
Any idea on how I can create a local variable with a directory listing list of the remote host in a bash script?
关于如何在 bash 脚本中使用远程主机的目录列表创建本地变量的任何想法?
回答by sehe
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 fto limit to files only
- 处理特殊文件名要好得多
- 更灵活 (
man find(1)) - 添加
-type f到仅限文件的限制
回答by crazyjul
Your command in quote is executed before executing the ssh command. Escaping the single quote should fix
在执行 ssh 命令之前执行引号中的命令。转义单引号应该修复

