0

I am trying to make a simple script to swap between my server and main computer to compile nginx, but everytime I run the script, it ignores the first variable in $nginxsrc which is $code. I stripped the build stuff out, because its not relevant to the question.

#!/bin/bash
home="/home/michael"
code="/src/nginx"
NGINX="nginx-1.13.11"
nginxsrc="$code/$NGINX"
echo "$code"
echo "$NGINX"
echo "$nginxsrc"

Here is what happens when it runs:

$ sudo bash /usr/local/bin/build-nginx
/src/nginx
nginx-1.13.11
/nginx-1.13.11

I have tried putting them in {} like so: nginxsrc="${code}/${NGINX}"

I have tried with and without quotes: nginxsrc=$code/$NGINX

My server is running ubuntu 16.04.4 LTS 64-bit with all the latest updates.

Bash version is 4.3.48

Obviously the expected result is:

/src/nginx
nginx-1.13.11
/src/nginx/nginx-1.13.11
2
  • 2
    The only way I can reproduce this is to put a literal carriage return character at the end of the code value and then to display the value of nginxsrc using echo -e. Commented May 20, 2018 at 18:23
  • Delete the line containing nginxsrc= and retype it slowly. Commented May 20, 2018 at 18:24

2 Answers 2

2

This will happen when you have carriage returns in your file -- your file was saved with DOS-style line endings:

Display such a file:

$ cat -e cr.sh
code="/src/nginx"^M$
NGINX="nginx-1.13.11"^M$
nginxsrc="$code/$NGINX"^M$
echo "$code"^M$
echo "$NGINX"^M$
echo "$nginxsrc"^M$

and run it with tracing on

$ bash -x cr.sh
+ code=$'/src/nginx\r'
+ NGINX=$'nginx-1.13.11\r'
+ nginxsrc=$'/src/nginx\r/nginx-1.13.11\r\r'
+ echo $'/src/nginx\r\r'
/src/nginx
+ echo $'nginx-1.13.11\r\r'
nginx-1.13.11
+ echo $'/src/nginx\r/nginx-1.13.11\r\r\r'
/nginx-1.13.11

Edit your files in an editor where you can set "unix" line endings, or fix it with dos2unix or
sed -i 's/\r$//'

Sign up to request clarification or add additional context in comments.

1 Comment

You bro! Worked like a charm!
1

Not sure how helpful it will be, but on my Ubuntu this actually works as expected:

jhartman@wieloryb:~$ bash /tmp/xxx
/src/nginx
nginx-1.13.11
/src/nginx/nginx-1.13.11

This sounds so unbelievable that there is any kind of bug in Bash around variables.

As you wrote, the snippet you've posted is just an extract. Perhaps somewhere in fragment not posted here there is an operation on your $code variable.

All I can suggest is to run it in debug using bash -x <script>, e.g.:

jhartman@wieloryb:~$   bash -x /tmp/xxx
+ home=/home/michael
+ code=/src/nginx
+ NGINX=nginx-1.13.11
+ nginxsrc=/src/nginx/nginx-1.13.11
+ echo /src/nginx
/src/nginx
+ echo nginx-1.13.11
nginx-1.13.11
+ echo /src/nginx/nginx-1.13.11
/src/nginx/nginx-1.13.11

This should help you to narrow down what is happening.

Good luck & best regards, Jarek

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.