1

how can I assign a dynamic value to variable? The simplest method I know about is by using a function. For example

fn(){
    VAR=$VAL
}
VAL=value
fn
echo $VAR

will output

value

but I want something simpler, like

VAR=$VAL
VAL=value
echo $VAR

to output

value

What command should I use? Preferably to be compatible with dash.

Thanks!

UPDATE: Removed #!/bin/sh in connection to dash. Thank "Ignacio Vazquez-Abrams" for the explanation!

UPDATE 2: Adding the source for my script to better understand the situation.

INPUT=`dpkg -l|grep ^rc|cut -d' ' -f3`
filter(){
    echo *$A*
}
for A in $INPUT;do find ~ -iname `filter`|grep ^$HOME/\\.|grep -iz --color $A;done

This script should help finding the remaining configuration files of removed packages.

mYself
  • 191
  • 1
  • 1
  • 11

3 Answers3

2

Okay, if function is not good, then maybe calling eval is okay?

export VAR='echo $VAL'
VAL=10
eval $VAR

This will display

10
Grzegorz
  • 3,207
  • 3
  • 20
  • 43
  • I'll rather stay away from _eval_. As I previously mentioned, it represents a security hole for the system. – mYself Oct 17 '12 at 22:40
  • How about export VAR='expr $VAL + 0' instead? expr will fail in case of VAL other than a number.... – Grzegorz Oct 17 '12 at 22:50
  • The _value_ should be in a form of _text_ combined with _another variable_. – mYself Oct 17 '12 at 23:03
  • I mean _value_ as a value of a variable, not as a mathematical expression. – mYself Oct 17 '12 at 23:09
  • I do not want to be quick in stating that then it is not possible, but I doubt it is. echo $VAR will take the 'textual' form of $VAR and simply display it. Because of that I think it is not possible without either setting VAR before, or evaluating it by eval. I will be looking at your thread to see if there is someone else that finds a way. Take care! – Grzegorz Oct 17 '12 at 23:19
  • I also think that isn't possible, but I thought I ask at least. Who knows, maybe there is someone who know something that I don't. – mYself Oct 17 '12 at 23:26
0

How about a simple function that sets value?

# export is needed so f() can use it.
export VAR

f() {
    VAR=$@
}

f 10
echo $VAR
f 20
echo $VAR

The code above will display:

10
20
Grzegorz
  • 3,207
  • 3
  • 20
  • 43
0

If I understand your needs, you want an indirection, so try the following shell code (tested with dash) :

var=foo
x=var
eval $x=another_value
echo $var

output :

another_value

finally:

Each times you need to modify var, you need to run eval $x=foobar

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • I read somewhere that _eval_ is not a good choice, because it presents a security hole. Therefore, I rather use a function for this. – mYself Oct 17 '12 at 22:28
  • With some shells (bash), you can use `declare` instead. – Gilles Quénot Oct 17 '12 at 22:29
  • I know about that, but as you said it work only with _bash_, which is generally slower than _dash_. I'll rather use a _function_ for this. – mYself Oct 17 '12 at 22:36