[BASH] PROBLEME VARIABLE

ZiopA -  
jisisv Messages postés 3678 Statut Modérateur -
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

  1. ric
     
    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
  2. ZiopA
     
    merci :) je vais testé même si la c'est du PHP :p je vais testé si ça peut marché en BASH
    0
  3. jisisv Messages postés 3678 Statut Modérateur 936
     
    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