0

So I've got a bash script in which I want to SSH onto one of my remote servers and run some commands. This is my code:

MYFUNCTION="
function my_function
{
    VAR=$(readlink -f current | sed 's/[^)
}
my_function
"

ssh -l ${USERNAME} ${HOSTNAME} "${MYFUNCTION}"

The problem is that the VAR variable is not being populated with the command output as it should. I've run the exact same command myself, and I get the desired output, but when doing it through SSH in the bash script, it doesn't work as expected. What am I doing wrong here?

2
  • my_function() { is POSIX-compliant syntax -- the way you're declaring your function is legacy ksh syntax supported by bash only for backwards compatibility. See wiki.bash-hackers.org/scripting/obsolete Commented Apr 10, 2018 at 19:58
  • Ideally, you should be using lowercase names for your own variables. See pubs.opengroup.org/onlinepubs/9699919799/basedefs/…, fourth paragraph -- all caps names are used for variables meaningful to the shell or operating system, whereas lowercase names are reserved for application use. Commented Apr 10, 2018 at 19:58

1 Answer 1

0

You are putting the code in double quotes, so the variables and commands are being executed on your local machine. Do echo "$MYFUNCTION" and you'll probably be surprised.

Try using a quoted here document:

# Note the single quotes in the next line
ssh -l "$USERNAME" "$HOSTNAME" <<'END_CODE'
function my_function
{
    cd www
    VAR=$(readlink -f current | sed 's/[^0-9]*//g')
    VAR2=$(find . -maxdepth 1 ! -newer "$VAR" ! -name "$VAR"| sort | sed '$!d')
}
my_function
END_CODE

Note also all the quoted variables.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.