title: Executing a string as a command in bash that contains pipes
body: <p>I'm trying to list some ftp directories. I can't work out how to make bash execute a command that contains pipes correctly.</p>
  
  <p>Here's my script:</p>
  
  <pre><code>#/bin/sh
  
  declare -a dirs=("/dir1" "/dir2")           # ... and lots more
  for d in "${dirs[@]}"
  do
      cmd='echo "ls /mydir/'"$d"'/*.tar*" | sftp -b - -i ~/mykey user@example.com 2&gt;&amp;1 | tail -n1'
      $cmd
  done
  </code></pre>
  
  <p>This just outputs:</p>
  
  <pre><code>"ls /mydir/dir1/*.tar*" | sftp -b - -i ~/mykey user@example.com 2&gt;&amp;1 | tail -n1
  "ls /mydir/dir2/*.tar*" | sftp -b - -i ~/mykey user@example.com 2&gt;&amp;1 | tail -n1
  </code></pre>
  
  <p>How can I make bash execute the whole string including the echo? I also need to be able to parse the output of the command.</p>