2014-10-30 138 views
0

我需要运行通过ssh一个多bash命令,用尽所有可能的尝试,但没有运气 -运行多bash命令不起作用

echo "3. All files found, creating remote directory on the server." 
ssh -t [email protected]$host bash -c "' 
       if [[ -d ~/_tmp ]]; then 
        rm -rf ~/_tmp/* 
       else 
        mkdir ~/_tmp 
       fi 
'" ; 

echo "4. Sending files ..." 
scp ${files[@]} [email protected]$host:~/_tmp/ ; 

这里是输出 -

[email protected]:/tmp$ ./remotecompile 
1. Please enter your id: 
user 
2. Please enter the names of the files that you want to compile 
    (Filenames *must* be space separated): 
test.txt 
3. All files found, creating remote directory on the server. 
Password: 
Unmatched '. 
Unmatched '. 
Connection to host.domain.com closed. 

请注意,我不想把每行2-3行的bash if-then-else-fi命令放到单独的文件中。

什么是正确的做法?

+1

顺便说一句,你需要引用更多的SCP命令:'SCP “$ {文件[@]}” “$ ID @ $主持人:〜/ _TMP /” ' - 不加引号,'$ {files [@]}'表现正好与'$ {files [*]}'相同,所有错误都与相同。 – 2014-10-30 23:46:49

回答

3

使用转义的heredoc使其文字内容通过。 (如果没有转义,即仅使用<<EOF,shell扩展将在本地处理 - 如果您在远程运行的代码中使用了变量,则会生成更有趣的转角情况)。

ssh "[email protected]$host" bash <<'EOF' 
if [[ -d ~/_tmp ]]; then 
    rm -rf ~/_tmp/* 
else 
    mkdir ~/_tmp 
fi 
EOF 

如果你想传递参数,在明确正确的方式这样做会更有意思(因为有壳解析参与的两个单独的层),但printf '%q'内置节省了一天:

args=("this is" "an array" "of things to pass" \ 
     "this next one is a literal asterisk" '*') 
printf -v args_str '%q ' "${args[@]}" 
ssh "[email protected]$host" bash -s "$args_str" <<'EOF' 
    echo "Demonstrating local argument processing:" 
    printf '%q\n' "[email protected]" 
    echo "The asterisk is $5" 
EOF 
1

这个工作对我来说:

ssh [hostname] '  
if [[ -d ~/_tmp ]]; then 
    rm -rf ~/_tmp 
else 
    mkdir ~/_tmp 
fi 
' 
+0

我同意这在这里的情况下工作正常。另一方面,当远程运行的代码包含自己的单引号时,它会变得笨重。 – 2014-10-30 23:48:11

+0

还有另外一个问题,对于每次需要输入密码的每个ssh/scp,有什么办法可以避免吗? – ramgorur 2014-10-30 23:53:34

+0

@ramgorur,在这种情况下,ControlMaster是你的朋友,如果你不想做正确的事情并使用RSA认证。 – 2014-10-30 23:54:34