title: How to do Variable Substitution with Flex/Lex and Yacc/Bison
body: <p><a href="http://en.wikipedia.org/wiki/Variable_%28programming%29#Interpolation" rel="nofollow noreferrer">Wikipedia's Interpolation Definition</a>
  I am just learning flex / bison and I am writing my own shell with it.  I am trying to figure out a good way to do variable interpolation.   My initial approach to this was to have flex scan for something like ~ for my home directory, or $myVar , and then set what the yyval.stringto what is returned using a look up function. My problem is, that this doesn't help me when text appears one token:</p>
  
  <pre><code>kbsh:/home/kbrandt% echo ~
  /home/kbrandt
  kbsh:/home/kbrandt% echo ~/foo
  /home/kbrandt /foo
  kbsh:/home/kbrandt%
  </code></pre>
  
  <p>The lex definition I have for variables:</p>
  
  <pre><code>\$[a-zA-Z/0-9_]+    {
      yylval.string=return_value(&amp;variables, (yytext + sizeof(char)));;
      return(WORD);
  }
  </code></pre>
  
  <p>Then in my Grammar, I have things like:</p>
  
  <pre><code>chdir_command:
      CD WORD { change_dir($2); }
      ;
  </code></pre>
  
  <p>Anyone know of a good way to handle this sort of thing? Am I going about this all wrong?</p>