Make sure that the gems directory exists before changing into it

The line:

  export GEM_HOME="$(cd ../gems && pwd -P)"

... only works if ../gems already exists.
Remove an extraneous trailing empty line