Assigning dynamic value to variable

1.4k Views Asked by At

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.

3

There are 3 best solutions below

1
On

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
3
On

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

6
On

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

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

This will display

10