How to use a bash profile function to connect remotely and access the remote terminal

0

I want to write a bash function locally (on MacOS), so when I run this function the first command is to get connected to an ubuntu Remote Desktop through ssh.

In a nutshell:

    my_func () {
    ssh blah blah blah;
    echo $VARIABLE;
}

The desired output is sth like /home/ubuntu/path/to/directory, but I get nothing. So I have the impression that my_func works only locally.

P.S. The environment variable $VARIABLE is set in the ~/.bashrc in the remote Desktop.

thanasissdr

Posted 2017-10-05T22:25:02.043

Reputation: 117

Where does $VARIABLE get set? Also the ;'s are unnecessary, bash treats new lines as command separators. Why do you think it would work remotely? – jesse_b – 2017-10-05T22:54:40.080

@Jesse_b Edited. – thanasissdr – 2017-10-05T22:58:15.343

So you want it to SSH to the remote machine and then execute the command: echo $VARIABLE? – jesse_b – 2017-10-05T22:59:01.663

@Jesse_b Exactly (basically, I want to do other things, but this is an important step to achieve the next steps). – thanasissdr – 2017-10-05T22:59:32.890

Answers

0

If I understand correctly this should work:

my_func () {
    ssh user@ip echo '$VARIABLE'
}

or if you have more commands you can do:

my_func () {
    ssh user@ip <<'EOF'
    echo $VARIABLE
    command2
    command3
EOF
}

You could also (my favorite for executing a lot of commands) put your commands in another file and do this:

my_func () {
    SOURCE_FILE='/path/to/file'
    cat "$SOURCE_FILE" | ssh user@ip
}

jesse_b

Posted 2017-10-05T22:25:02.043

Reputation: 101

2I think you need to escape the variable like this: "\$VARIABLE" or use single quotes like this '$VARIABLE'. – gogators – 2017-10-05T23:06:24.377

@Jesse_b Unforunately, none of these works. I manage to get connected to the remote terminal, but then when I echo, nothing happens. – thanasissdr – 2017-10-05T23:26:38.987

@gogators Thanks! You're right, the local machine was trying to expand the variable before sending it to the remote machine. – jesse_b – 2017-10-05T23:42:05.887