View previous topic :: View next topic |
Author |
Message |
nephros Advocate
Joined: 07 Feb 2003 Posts: 2139 Location: Graz, Austria (Europe - no kangaroos.)
|
Posted: Thu Mar 06, 2003 2:02 pm Post subject: bash scriping: ways to call a variable |
|
|
I have a strange bash question.
In the usual (init.d, profile...) script one comes across various ways of calling variables. The ones I have found are those:
VARIABLE="foobar"
$VARIABLE
${VARIABLE)
"$VARIABLE"
$"VARIABLE"
what is the difference, and when to use which? _________________ Please put [SOLVED] in your topic if you are a moron. |
|
Back to top |
|
|
fifo Guru
Joined: 14 Jan 2003 Posts: 437
|
Posted: Thu Mar 06, 2003 2:56 pm Post subject: |
|
|
Note that $"VARIABLE" is just the string "VARIABLE", not the variable itself.
"$VARIABLE" is an empty string with the contents of VARIABLE interpolated into it, which of course just means the same as $VARIABLE. You would normally use this form if you wanted to insert further characters, for example, "*$VARIABLE*" will produce the string "*foobar*".
Now suppose you wanted "_foobar_" instead. You can't use "_$VARIABLE_", because this refers to the variable VARIABLE_, not VARIABLE. This is where the braces come in; use "_${VARIABLE}_" instead.
Some people like to always use braces whether they're needed or not. This is the standard when writing ebuilds. The consistency makes it harder to accidentally refer to the wrong variable, and makes it easier to search for all occurances of a variable a file. |
|
Back to top |
|
|
TGL Bodhisattva
Joined: 02 Jun 2002 Posts: 1978 Location: Rennes, France
|
Posted: Thu Mar 06, 2003 4:34 pm Post subject: |
|
|
I also have a question about bash which is probably related to this one. Here is what I would like to be able to do, in a script:
- define a string variable $A, which contains "value of B is: $B" (with $B not defined yet)
- define the variable $B
- "echo" the content of $A, with $B replaced by its newly defined value.
I've tried a lot of combinations of singlequote, doublequote, backslash, etc., but now I'm really wondering if it is possible. Any idea?
Thanks. |
|
Back to top |
|
|
fifo Guru
Joined: 14 Jan 2003 Posts: 437
|
Posted: Thu Mar 06, 2003 4:50 pm Post subject: |
|
|
Not sure if this is exactly what you want, but you could do something like:
Code: |
$ A='The value of B is: $B'
$ B="foo"
$ eval echo $A
|
|
|
Back to top |
|
|
TGL Bodhisattva
Joined: 02 Jun 2002 Posts: 1978 Location: Rennes, France
|
Posted: Thu Mar 06, 2003 5:25 pm Post subject: |
|
|
Thanks a lot fifo, "eval" is really the command I was looking for. I didn't know that it exists.
Thanks again. |
|
Back to top |
|
|
|