I'm working on a bash script to help migrate KVM virtual machines, but I'll be using dummy code to explain what is going on.
I'm using functions to break up the tasks perform on a remote servers and to get the info needed from the user while displaying the info the user needs to answer the questions. Down below will be 3 scripts just to show the 3 ways I have worked from to figure out what is going on.
The first doesn't involve any ssh and works like it should
#!/bin/bash getname() { echo -n "Name: " read name } gethobby() { echo -n "hobby: " read hobby } showresults() { echo "$name" echo "$hobby" } getname gethobby showresults
This second script is the way I'm trying to get it to work. I will be running a function on a remote server by ssh, but the values of the variables aren't accessible from other functions like I need them to be
#!/bin/bash server1='10.1.1.153' getname() { echo -n "Name: " read name } gethobby() { uptime echo -n "hobby: " read hobby } showresults() { echo "$name" echo "$hobby" } getname echo -n "server: " read sname ssh -t sysadmin@"${!sname}" "$(typeset -f); gethobby" showresults
This third script works, but isn't something that would be used in production I think. Due to having to run a bunch of ssh with commands there are disconnect lines all over the place which makes the output confusing. Though with this method I can access the values I need from the variables.
#!/bin/bash server1='10.1.1.153' getname() { echo -n "Name: " read name } gethobby() { ssh -t sysadmin@"${!sname}" "$(typeset -f); uptime" echo -n "hobby: " read hobby } showresults() { echo "$name" echo "$hobby" } getname echo -n "server: " read sname gethobby showresults
So is there any way to get script 2 to work?
Update: Yes I know test is a bad name and using it over is bad, but this is not the actual code since the actual code is a lot bigger and more complicated.
You might be right about the function part, but I have had many programs that have worked with ssh user@ip function work. I believe it works since it expands and just run all the stuff inside the function without having to do ssh individual commands.
The second script works except for getting the value back from the function. It is empty when echoing it instead of having the value the user input.
test
) as a shell builtin is a bad idea...