在ssh上运行multiline bash命令不起作用

时间:2014-10-30 23:42:09

标签: bash ssh

我需要在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/ ; 

这是输出 -

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.

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

这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:3)

使用转义的heredoc来传递其文字内容。 (没有转义,即只使用<<EOF,shell扩展将在本地处理 - 如果你在远程运行的代码中使用变量,则会产生更有趣的极端情况。)

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

如果你想传递参数,那么以明确正确的方式这样做会变得更有趣(因为涉及两个单独的shell解析层),但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

答案 1 :(得分:1)

这对我有用:

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