Simon Bagley
Simon Bagley

Reputation: 320

How to concatenate string variables in a Bash script

The following script produces an unexpected output

#!/bin/bash
#
MY_DIRECTORY=.
OUTPUT_DIR="$MY_DIRECTORY""/build_test"
echo "MY_DIRECTORY is $MY_DIRECTORY"
echo "OUTPUT_DIR is $OUTPUT_DIR"

I expect the following:

MY_DIRECTORY is .
OUTPUT_DIR is ./build_test

but it actually produces:

MY_DIRECTORY is .
/build_testis .

Can anyone tell me what I'm doing wrong? Note I am running GNU bash version 4.4.12(3)-release in a Cygwin command shell under Windows 10.

Upvotes: 0

Views: 1334

Answers (2)

Jon
Jon

Reputation: 3671

This is a problem with mixed Unix and Windows line endings. You have a carriage return at the end of the MY_DIRECTORY= line. The carriage return is causing part of the second output line to be overwritten. I can replicate your output on my Cygwin installation.

If you run the script through dos2unix it will work as expected.

To prevent this kind of thing happening again, configure your text editor to save files using Unix line endings.

Upvotes: 2

MaJoR
MaJoR

Reputation: 1044

The script is fine. I tried to run in on my system, and is giving the expected output. I am running Bash version 4.38.48 on Arch.

If you are on Windows, you can try bash on Windows as well, but I do not think that it should affect the output.

Upvotes: 2

Related Questions