首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在ssh上运行多行bash命令不能工作。

在ssh上运行多行bash命令不能工作。
EN

Stack Overflow用户
提问于 2014-10-30 23:42:08
回答 2查看 2K关注 0票数 1

我需要在ssh上运行一个多行bash命令,所有可能的尝试都用尽了,但没有运气--

代码语言:javascript
复制
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/ ; 

这是输出--

代码语言:javascript
复制
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,如果-否则-fi命令到不同的文件。

正确的方法是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-10-30 23:44:03

使用转义的本地文档来传递其文字内容。(没有逃跑).仅使用<<EOF,shell展开就会在本地处理--如果在远程运行的代码中使用变量,就会出现更有趣的角落情况)。

代码语言:javascript
复制
ssh "$id@$host" bash <<'EOF'
if [[ -d ~/_tmp ]]; then
    rm -rf ~/_tmp/*
else
    mkdir ~/_tmp
fi
EOF

如果您想传递参数,以一种明确正确的方式这样做会变得更有趣(因为涉及两个单独的shell解析层),但是printf '%q'内置可以节省时间:

代码语言:javascript
复制
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
票数 4
EN

Stack Overflow用户

发布于 2014-10-30 23:47:01

这对我来说很管用:

代码语言:javascript
复制
ssh [hostname] '       
if [[ -d ~/_tmp ]]; then
   rm -rf ~/_tmp
else
   mkdir ~/_tmp
fi
'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26665307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档