1

If I set a variable in a shell script and then try to use it to create another variable, it doesn't seem to get substituted correctly. Example:

#!/bin/bash
X=/software/xxx
echo variable X = $X
echo path using variable: $X/yyy
echo path without variable: /software/xxx/yyy

This outputs:

variable X = /software/xxx
/yyy using variable: /software/xxx
path without variable: /software/xxx/yyy

I had expected the second output line to be:

path using variable: /software/xxx/yyy

I have tried various combinations of quotes and using ${X}, but all to no avail.

I'm new to shell scripting (coming from a Windows background), so I'm sure there is something really simple that I'm missing here.

In case anyone wonders why I want to do this, the background to this is that I need to write a shell script that takes a relative pathname parameter, determines its absolute pathname, then sets CLASSPATH with a number of jar files in that directory before invoking a Java program:

#!/bin/bash
DIR=`readlink -fn $1`
export CLASSPATH=$DIR/x.jar:$DIR/y.jar
java progname
cliveb
  • 13
  • 1
  • 5
  • 2
    Quoting is normally the reason of the problems in the world. – fedorqui Nov 24 '14 at 12:36
  • I just ran your example, and I get the expected output. Try running with bash -x and seeing what $X is set to. I suspect X is not what you think it is. – Bitdiot Nov 24 '14 at 12:52

1 Answers1

0

You have carriage return (CR) character at the end of your X= variable declaration:

#!/bin/bash

X=/software/xxx^M
echo variable X = $X
echo path using variable: $X/yyy

(where ^M represents ONE special character - CR). I assume your editor doesn't show it. Try to open your script with vim. Windows and Linux marks newline in a different way (check wiki) . I suppose you're using some Windows editor.

Please read Bash Pitfalls webpage. I'm sure you can learn a lot from there.

btw. one way to enter ^M at vim: go to insert-mode i, than press: CTRL+k, M, ENTER

pawel7318
  • 3,383
  • 2
  • 28
  • 44
  • You can also remove all `^M` characters from the file with `vim`: `:%s/^M$//`. Vim can be painful for beginners but `vimtutor` will make you love it. – pawel7318 Nov 24 '14 at 13:38
  • Many thanks for the answers. There were indeed extra \r characters in the file. (I had prepared it on Windows using emacs - I dislike vi as an editor). bash -x revealed the situation. Have recreated the file from scratch on Linux and it worked just fine. – cliveb Nov 24 '14 at 13:59
  • You can use `vi -b` to edit a file in "binary mode" which shows extra `^M` chars at the end when running on Linux. – Charlie Reitzel Aug 31 '21 at 22:59