1

I'm stumped here: I have a bash script which reads a series of variables out of a .env file, and then runs a few commands using those values. But the behavior is completely confusing to me. Here's a simplified example:

The contents of my .env file are:

GCS_BUCKET_NAME="my-bucket"
GCS_ROOT_FOLDER="my-folder"

And the script is:

if [ -f .env ]; then
  #load the .env file
  echo "Loading environment..."
  source .env &>/dev/null
  echo ""
  echo "GCS Bucket: $GCS_BUCKET_NAME"
  echo "GCS Root Folder: $GCS_ROOT_FOLDER"
  echo ""
  PATH_TO_FOLDER=gs://${GCS_BUCKET_NAME}/${GCS_ROOT_FOLDER}
  echo $PATH_TO_FOLDER
else
  echo "No .env file found."
fi

The output of running this script is:

Loading environment...

GCS Bucket: my-bucket
GCS Root Folder: my-folder

/my-foldercket

...How am I winding up with /my-foldercket?

If I instead define the variables inline:

#!/bin/bash

GCS_BUCKET_NAME="my-bucket"
GCS_ROOT_FOLDER="my-folder"
echo ""
echo "GCS Bucket: $GCS_BUCKET_NAME"
echo "GCS Root Folder: $GCS_ROOT_FOLDER"
echo ""  
PATH_TO_FOLDER=gs://${GCS_BUCKET_NAME}/${GCS_ROOT_FOLDER}
echo $PATH_TO_FOLDER

I get this output:

GCS Bucket: my-bucket
GCS Root Folder: my-folder

gs://my-bucket/my-folder

...which is what I'd expect.

What on earth is going on here?

DanM
  • 7,037
  • 11
  • 51
  • 86
  • Similar question: [shell: strange string concatenation behavior](https://stackoverflow.com/q/41219148/4518341) – wjandrea Apr 07 '20 at 15:22
  • @wjandrea yes, a similar question indeed -- but not one I was able to find with the search terms I had in mind :) In other words, it's similar only once you realize that the problem is specifically related to concatenation. – DanM Apr 07 '20 at 15:44
  • @DanM, that's the purpose of close-as-dupe: To have a new-and-different set of search terms pointing to an existing Q&A pair. So -- feature, not a bug. :) – Charles Duffy Apr 07 '20 at 15:48
  • @CharlesDuffy in retrospect my comment sort of implied "...so it shouldn't be closed", which wasn't the intent. Definitely a legitimate move. – DanM Apr 07 '20 at 16:28

1 Answers1

2

Your .env file has CRLF line endings. I can reproduce the behaviour by putting CRs in the variables:

GCS_BUCKET_NAME=$'my-bucket\r'
GCS_ROOT_FOLDER=$'my-folder\r'
echo gs://${GCS_BUCKET_NAME}/${GCS_ROOT_FOLDER}  # -> /my-foldercket

For how to fix it, see Remove carriage return in Unix, and make sure your editor is set to save with LF line endings.

wjandrea
  • 28,235
  • 9
  • 60
  • 81