英文:
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 "$dir1" "$dir2"
chmod 600 "$dir2"
# 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 << EOF
cp -r "$dir1" "$dir2"
chmod 600 "$dir2"
# 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论