如何使用SSH运行带有变量的bash脚本?

huangapple go评论96阅读模式
英文:

How to SSH and run a bash script with variables?

问题

我有一个脚本文件(sub.sh),其中包含变量,例如:

cp -r "$dir1" "$dir2"
chmod 600 "$dir2"
# 和许多其他命令...

我还有另一个脚本(main.sh),用于准备这些变量,将它们导出到环境中,并通过SSH在另一台服务器上运行上面的脚本文件。我尝试了以下命令,但它不起作用,因为变量在传递到服务器之前没有经过预处理:

cat ./sub.sh | ssh $user@$ip

我知道我可以使用Heredoc 来实现这一点:

ssh $user@$ip << EOF
  cp -r "$dir1" "$dir2"
  chmod 600 "$dir2"
  # 和许多其他命令...
EOF

但是这个脚本很长,我想将文件拆分以使代码更清晰。如何实现这一点?谢谢。

英文:

I have a script file (sub.sh) with the variable inside, for example:

cp -r &quot;$dir1&quot; &quot;$dir2&quot;
chmod 600 &quot;$dir2&quot;
# and many other commands...

I have another script (main.sh) that prepare the variables, export them to the environment, and run the script file above on another server via SSH. I tried the following command but it doesn't work because the variables are not pre-processed before passing to the server:

cat ./sub.sh | ssh $user@$ip

I know that I can use Heredoc like this:

ssh $user@ip &lt;&lt; EOF
  cp -r &quot;$dir1&quot; &quot;$dir2&quot;
  chmod 600 &quot;$dir2&quot;
  # and many other commands...
EOF

but the script is long and I want to split the file to make the code cleaner.

How can I achieve this? Thanks.

答案1

得分: 1

你可以将你的变量存储在一个名为config.sh的.sh文件中。

在执行时,你可以使用以下命令:./sub.sh config.sh

config.sh中的所有变量将被用作命名变量(你可以通过名称访问它们),例如$dir1

英文:

You can store your variables in a .sh file like config.sh

When executing you can use following command ./sub.sh config.sh

All the variables inside config.sh will be used as named variables (you can access them via name )
like $dir1

答案2

得分: 1

使用 declare -p 传递变量:

{ declare -p dir1 dir2; cat ./sub.sh; } | ssh $user@$ip
英文:

Use declare -p to pass variables :

{ declare -p dir1 dir2; cat ./sub.sh; } | ssh $user@$ip

huangapple
  • 本文由 发表于 2023年8月5日 12:05:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76840105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定