title: bash scripting: build a command then execute
body: <p>I'm trying to make a function that basically takes in arguments like <code>f hello there my friend</code> and searches a directory using <code>find</code> for all occurences of any of those strings, so it would be <code>find | grep 'hello\|there\|my\|friend'</code>.  I'm new to shell scripting, but my code is below:</p>
  
  <pre><code>function f { 
    cmd="find | grep '"
    for var in "$@"
    do 
      cmd="$cmd$var\\|"
    done
    cmd="${cmd%\\|}'"
    echo "$cmd"
    $cmd 
  }
  </code></pre>
  
  <p>When I execute the command, I get this:</p>
  
  <pre><code># f hello there my friend
  find | grep 'hello\|there\|my\|friend'
  find: `|': No such file or directory
  find: `grep': No such file or directory
  find: `\'hello\\|there\\|my\\|friend\'': No such file or directory
  </code></pre>
  
  <p>Why does it not work, and how can I make it work?  I imagine it's something to do with the string not being converted to a command, but I don't know enough about how shell scripting works to figure it out.</p>