Bash脚本在上一个命令之前运行一个命令.我要他们一个接一个 [英] Bash script runs one command before previous. I want them one after the other

查看:84
本文介绍了Bash脚本在上一个命令之前运行一个命令.我要他们一个接一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的脚本的一部分如下:

So part of my script is as follows:

ssh user@$remoteServer "
    cd ~/a/b/c/;
    echo -e 'blah blah'
    sleep 1 # Added this just to make sure it waits.
    foo=`grep something xyz.log |sed 's/something//g' |sed 's/something-else//g'`
    echo $foo > ~/xyz.list
    exit "

在我的输出中,我看到:

In my output I see:

grep: xyz.log: No such file or directory
blah blah

当我SSH到服务器时,xyz.log确实存在于〜/a/b/c/

Whereas when I ssh to the server, xyz.log does exist within ~/a/b/c/

为什么在echo语句之前执行grep语句?

Why is the grep statement getting executed before the echo statement?

有人可以帮忙吗?

推荐答案

此处的问题是您在反引号中的命令正在本地上运行,而不是在SSH连接的远程端上运行.因此,它可以在您完全连接到远程系统之前运行! (对于所有使用双引号引起来的扩展都是如此,因此echo $foo中的$foo也是如此.)

The problem here is that your command in backticks is being run locally, not on the remote end of the SSH connection. Thus, it runs before you've even connected to the remote system at all! (This is true for all expansions that run in double-quotes, so the $foo in echo $foo as well).

使用带引号的heredoc保护您的代码免受本地评估:

Use a quoted heredoc to protect your code against local evaluation:

ssh user@$remoteServer bash -s <<'EOF'
    cd ~/a/b/c/;
    echo -e 'blah blah'
    sleep 1 # Added this just to make sure it waits.
    foo=`grep something xyz.log |sed 's/something//g' |sed 's/something-else//g'`
    echo $foo > ~/xyz.list
    exit
EOF

如果要从本地传递变量,则简单的方法是使用位置参数:

If you want to pass through a variable from the local side, the easy way is with positional parameters:

printf -v varsStr '%q ' "$varOne" "$varTwo"
ssh "user@$remoteServer" "bash -s $varsStr" <<'EOF'
  varOne=$1; varTwo=$2 # set as remote variables
  echo "Remote value of varOne is $varOne"
  echo "Remote value of varTwo is $varTwo"
EOF

这篇关于Bash脚本在上一个命令之前运行一个命令.我要他们一个接一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆