简体   繁体   English

通过SSH运行多行bash命令不起作用

[英]running multiline bash command over ssh does not work

I need to run a multi-line bash command over ssh, all possible attempt exhausted but no luck -- 我需要在ssh上运行多行bash命令,所有可能的尝试都已用尽,但是没有运气-

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

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

Here is the output -- 这是输出-

user@linux:/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.

Please note, I do not want to put every 2-3 lines of bash if-then-else-fi commands into separate files. 请注意,我不想将每2-3行bash if-then-else-fi命令放入单独的文件中。

What is the right way to do it? 正确的做法是什么?

Use an escaped heredoc to have its literal contents passed through. 使用转义的heredoc传递其文字内容。 (Without the escaping, ie. using just <<EOF , shell expansions would be processed locally -- making for more interesting corner cases if you used variables inside your remotely-run code). (不进行转义,即仅使用<<EOF ,将在本地处理shell扩展-如果在远程运行的代码中使用变量,则会导致更有趣的极端情况)。

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

If you want to pass arguments, doing so in an unambiguously correct manner gets more interesting (since there are two separate layers of shell parsing involved), but the printf '%q' builtin saves the day: 如果您想传递参数,那么以一种明确正确的方式进行操作会变得更加有趣(因为涉及到两个单独的外壳解析层),但是内置的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 "$id@$host" bash -s "$args_str" <<'EOF'
  echo "Demonstrating local argument processing:"
  printf '%q\n' "$@"
  echo "The asterisk is $5"
EOF

This works for me: 这对我有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM