LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to make shell variable don't expand immediately (https://www.linuxquestions.org/questions/programming-9/how-to-make-shell-variable-dont-expand-immediately-732621/)

linuxgentoo 06-12-2009 11:40 PM

How to make shell variable don't expand immediately
 
assumption:
X=/home/user
Y=${X}/tmp

When the X variable is changed,However the Y variable isn't changed according to X's change,Y already expand when define it.

Is there any way that expand variable when only referring Y variable ,not define it?

Thanks

jlinkels 06-13-2009 08:36 AM

Uhm.. this is not called expanding I believe. Expanding is when file* becomes file1 file2 file34 etc. IMHO.

As for your problem, Y get the value of $X when you say it has to get it, i.e. Y=$X gives the value of $X to Y, and no matter what happens to X afterwards, Y won't change. It is one of the fundamentals of programming in this type of languages.

In an ordinary programming language you would create a function getY or so which would look at $X at the moment of calling. But Bash doesn't provide function return values, at least not easily.

The only thing you can do is NOT using Y, but always ${X}/tmp when you need this string. You can beautify your program a bit more to define /tmp just once Z="/tmp", so if you have to change this value you'd only have to do it in one place. You reference would become: ${X}/${Z} wherever you use $Y now.

jlinkels


All times are GMT -5. The time now is 08:25 PM.