如何将多个命令存储在bash变量中(类似于cat otherscript.sh):

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

How to store multiple commands in a bash variable (similar to cat otherscript.sh)

问题

对于工作需要连接到测试节点并建立VNC连接以远程查看桌面。这是一个手动过程,需要按顺序执行一堆命令。非常适合使用Bash脚本进行自动化。问题在于,某些命令需要在建立SSH连接后在远程节点上执行。

目前,我已经将其工作方式如下,其中startVNC是一个单独的Bash文件,存储了需要在建立SSH连接后在远程节点上执行的命令。

cat startVNC | sed -e "s/$scaling/$scaling/" -e "s/$address/$address/" -e "s/$display/$display/" | ssh -X maintain@$host

对于我的问题,startVNC的内容实际上不重要,只要能按顺序执行多个命令即可。它可以是:

echo "hello"
sleep 1
echo "world"

尽管对于个人使用来说,这个解决方案是可以接受的,但我觉得使用两个单独的Bash文件有点麻烦。如果我想分享这个文件(我确实想这样做),最好是一个文件。我的问题是,是否可以以某种方式模仿cat的输出,使用一个变量?

英文:

For work I'm needing to connect to test nodes and establish a vnc connection so you can see the desktop remotely. It's a manual process with a bunch of commands that need to be executed in order. Perfect for automation using a bash script. The problem is that some commands need to be executed on the remote node after an ssh connection is established.

Currently I've got it working like this, where startVNC is a seperate bash file which stores the commands that need to be executed on the remote node after an ssh connection is established.

cat startVNC | sed -e "s/$scaling/$scaling/" -e "s/$address/$address/" -e "s/$display/$display/" | ssh -X maintain@$host

For my question the contents of startVNC don't really matter, just that multiple commands can be executed in order. It could be:

echo "hello"
sleep 1
echo "world"

While for personal use this solution is fine, I find it a bit of a bother that this needs to be done using two separate bash files. If I want to share this file (which I do) it'd be better if it was just one file. My question is, is it possible to mimic the output from cat in some way using a variable?

答案1

得分: 0

你可以这样做:

a="echo 'hello'\nsleep 2\necho world\n"
echo -e $a
# 输出-> echo 'hello'
# 输出-> sleep 2
# 输出-> echo world
echo -e $a | bash
# 输出-> hello
# 等待 2 秒
# 输出-> world

echo 中的 -e 选项允许解释 \n

英文:

Well, you could do:

a="echo 'hello'\nsleep 2\necho world\n"
echo -e $a
#  output-> echo 'hello'
#  output-> sleep 2
#  output-> echo world
echo -e $a | bash
#  output-> hello
#  waiting 2 secs
#  output-> world

The -e in echo enables the interpretation of the \n.

huangapple
  • 本文由 发表于 2023年6月1日 17:41:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76380579.html
匿名

发表评论

匿名网友

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

确定