I have created myscript.sh file in one of local linux server. I am trying to pass the variables and functions defined in(myscript.sh) to remote machine.
my_var="Myvar Value"
getIPAddress()
{
echo $my_var
ip_address=$(hostname -i)
echo $ip_address
}
ssh user@remote "$(typeset -f getIPAddress); getIPAddress"
I am only getting the ip_address but not getting the value of $my_var. Is there a way to handle this.
CodePudding user response:
You don't pass the value of the variable to the remote side. On the remote host, you re-create the function, but you don't create the variable the function depends on. You could do it with
ssh user@remote "$(typeset -f getIPAddress); my_var='$my_var'; getIPAddress"
or a bit shorter
ssh user@remote "$(typeset -f getIPAddress); my_var='$my_var' getIPAddress"
Note that in the first form, my_var
is treated as shell variable, while in the second form, my_var
is an environment variable inside your function.
I added quoting to catch the case that my_var
contains white space.
CodePudding user response:
Like this:
for server in foo bar base; do
ssh user@$server <<-'EOF'
my_var="Myvar Value"
getIPAddress() {
echo "$my_var"
ip_address="$(hostname -i)"
echo "$ip_address"
}
getIPAddress
EOF
done
Using shell here-doc.
See
man bash | less /here-doc