Michael
Michael

Reputation: 53

SSH with EOF correctly sets $PATH, but why doesn't it work without EOF?

I'd like to understand why ssh doesn't set the $PATH to whatever is determined in .profile, but seems to do it when ssh uses EOF.

I'd like to run this line in my script:

DIR_EXPANDED=`ssh $TOADDRESS "$(typeset -f get_dir); get_dir $DIR $DBNAME"`

Where get_dir is defined like so:

function get_dir() {
  DIRECTORY_NAME=$1
  DBNAME=$2

  if [ -z "$DIRECTORY_NAME" ]; then
    echo "Enter Directory Name:"; read DIRECTORY_NAME
  elif [ -n "$2" ]; then
    . oraenv $DBNAME
  fi
  DIRECTORY=`sqlplus -s '/ as sysdba' << EOF
  set pages 0 head off feed off

  select directory_path from all_directories where directory_name='$DIRECTORY_NAME';

EOF`

  echo $DIRECTORY;
}

However, running the script results in the error

ksh[10]: .: oraenv: cannot open [No such file or directory]

Which I've found is because the path is not correctly set when ssh'ing as demonstrated by this:

ssh $TOADDRESS 'echo $PATH'
/usr/local/bin:/usr/bin

Through trial and error I've found that this works:

TODIR_EXPANDED=`ssh $TOADDRESS << EOF
  $(typeset -f get_dir); get_dir $TODIR $TODBNAME
EOF`

Can someone explain why ssh works this way? As well as how/if it would be possible to use the one-liner I first described?

Upvotes: 0

Views: 554

Answers (1)

mirabilos
mirabilos

Reputation: 5327

If you use ssh HOST command, a non-interactive shell is loaded, which does not read the .profile for login shells or .kshrc for interactive shells.

If you use ssh HOST it starts an interactive shell (albeit without a pseudo-TTY allocated) and reads .kshrc (or similar, depending on the actual shell spawned), and then continues reading commands from standard input.

So, if you wish to make the functions available, you can do it like this:

DIR_EXPANDED=$(ssh $TOADDRESS ". ./.kshrc; $(typeset -f get_dir); get_dir $DIR $DBNAME")

(I’ve also changed the deprecated form of command substitution (using the grave accent) to the modern/POSIX form, as this fixes some bugs.)

Upvotes: 1

Related Questions