0

I am trying to Concatenate variables with Strings in my bash script, the variables are being read independently but whenever I try to concatenate them, it doesn't recognize the variable values. ex-

echo $CONFIG_PROTOCOL (Prints the variable value, HTTP) 

echo $CONFIG_PROTOCOL'://'$CONFIG_SERVER_SOURCE:$CONFIG_PORT'/api/creation/objects/export?collection.ids='$sf

The above echo with the URL prints out /api/creations/objects/export?collection.ids=value_1, while it should print out http://localhost:8080/api/creation/objects/export?collection.ids=value_1

Any inputs will be appreciated.

1
  • 2
    Bad problem description: "it doesn't work". Good problem description: "It writes out ://:/api/creation/objects/export?collection.ids= but I expected HTTP://example.com:8080/api/creation/objects/export?collection.ids=42, because as you can see from this paste from my terminal (etc etc)." Please edit your question and add a good problem description Commented Feb 21, 2018 at 20:30

2 Answers 2

2

This happens because $CONFIG_PORT has a trailing carriage return. Here's a MCVE:

CONFIG_PROTOCOL="http"
CONFIG_SERVER_SOURCE="example.com"
CONFIG_PORT="8080"
sf="42"

# Introduce bug:
CONFIG_PORT+=$'\r'

echo $CONFIG_PROTOCOL'://'$CONFIG_SERVER_SOURCE:$CONFIG_PORT'/api/creation/objects/export?collection.ids='$sf

When executed, this prints:

/api/creation/objects/export?collection.ids=42

When you comment out the buggy line, you get:

http://example.com:8080/api/creation/objects/export?collection.ids=42

In both cases, echo will appear to show the correct values because echo is a tool for showing text to humans and not useful for showing the underlying data. printf '%q\n' "$CONFIG_PORT" will instead show it in an unambiguous format:

$ echo $CONFIG_PORT
8080

$ printf '%q\n' "$CONFIG_PORT"
$'8080\r'

The best way to fix this is to ensure that whatever supplies the value does so correctly. But the easiest way is to just strip them:

echo $CONFIG_PROTOCOL'://'$CONFIG_SERVER_SOURCE:$CONFIG_PORT'/api/creation/objects/export?collection.ids='$sf | tr -d '\r'
Sign up to request clarification or add additional context in comments.

1 Comment

Just at the same time, I was able to verify that I had properties file in DOS format. It was indeed the line endings causing the issue. Thanks much!
0
echo "$CONFIG_PROTOCOL://$CONFIG_SERVER_SOURCE:$CONFIG_PORT/api/creation/objects/export?collection.ids=$sf"

Try above echo statement

1 Comment

Doesn't work. It still prints /api/creations/objects/export?collection.ids=value_1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.