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?

  • `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 http://wiki.bash-hackers.org/scripting/obsolete – Charles Duffy Apr 10 '18 at 19:58
  • Ideally, you should be using lowercase names for your own variables. See http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html, fourth paragraph -- all caps names are used for variables meaningful to the shell or operating system, whereas lowercase names are reserved for application use. – Charles Duffy Apr 10 '18 at 19:58

1 Answers1

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.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352