[BASH] PROBLEME VARIABLE

Fermé
ZiopA - 6 avril 2005 à 01:48
jisisv Messages postés 3645 Date d'inscription dimanche 18 mars 2001 Statut Modérateur Dernière intervention 15 janvier 2017 - 24 juin 2005 à 07:37
Bonsoire, j'ai un probleme pour la création de variable:

je vouderai faire une varaible extentible... c'est à dire

var_lien="monlien.html"
var_site="http://ztpr.free.fr"

read myvar

echo "$var_$myvar"

voilà pour que ça affiche "monlien.html" si on tape "lien"
ou "http://ztpr.free.fr" si l'on tape site

:) je vous remerci d'avance...

3 réponses

Il s'agit de variable DYNAMIQUE et non extensible.
Essaie ce code :
$var_lien="monlien.html";
$var_site="http://ztpr.free.fr";
$varprefixe="var_";
$myvar ="site";
echo "La variable myvar est : " . $myvar . "<br />\n";
echo "La variable est : " . $var_lien . "<br />\n";
echo "La variable dynamique est : " . ${$varprefixe . $myvar};
0
merci :) je vais testé même si la c'est du PHP :p je vais testé si ça peut marché en BASH
0
jisisv Messages postés 3645 Date d'inscription dimanche 18 mars 2001 Statut Modérateur Dernière intervention 15 janvier 2017 934
24 juin 2005 à 07:37
Ceci peut résoudre le problème:
johand@horus:~$ var_lien="monlien.html"
johand@horus:~$ var_site="http://ztpr.free.fr"
johand@horus:~$ read myvar
lien
johand@horus:~$ thevar=var_$myvar
johand@horus:~$ echo $thevar
var_lien
johand@horus:~$ echo ${!thevar}
monlien.html


Extrait de man bash
If the first character of parameter is an exclamation point, a level of
       variable  indirection  is introduced.  Bash uses the value of the vari-
       able formed from the rest of parameter as the  name  of  the  variable;
       this  variable  is  then expanded and that value is used in the rest of
       the substitution, rather than the value of parameter itself.   This  is
       known as indirect expansion.  The exceptions to this are the expansions
       of ${!prefix*} and ${!name[@]} described below.  The exclamation  point
       must  immediately  follow the left brace in order to introduce indirec-
       tion.

Hope this helps
0