gpt4 book ai didi

linux - Bash 脚本在前一个命令之前运行一个命令。我想要一个接一个

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:45:02 24 4
gpt4 key购买 nike

所以我的部分脚本如下:

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 "

在我的输出中我看到:

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

而当我通过 ssh 连接到服务器时,xyz.log 确实存在于 ~/a/b/c/中

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

有人可以帮忙吗?

最佳答案

这里的问题是您在反引号中的命令正在本地 运行,而不是在 SSH 连接的远程端运行。因此,它甚至在您连接到远程系统之前就已经运行了! (对于所有在双引号中运行的扩展都是如此,因此 echo $foo 中的 $foo 也是如此)。

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

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

如果你想从本地传递一个变量,简单的方法是使用位置参数:

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

关于linux - Bash 脚本在前一个命令之前运行一个命令。我想要一个接一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36025822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com