title: bash: run "find --exec ..." command with terminating "\;", all stored in variable?
body: <p>I'm trying to find a way in a bash script to build a <code>find</code> command with a <code>-exec</code> stored in a variable, and I can't get the terminating <code>\;</code> to be recognized correctly if it's part of the variable.</p>
  
  <p>I can work around it by adding the <code>\;</code> when I invoke the command via the variable:</p>
  
  <pre><code>local all_the_things=($($cmd \;))
  </code></pre>
  
  <p>I'm not sure though how that might interact when <code>$cmd</code> stores a different command (there are several quite different contexts with different ways to get the list I need, only one of which is via a <code>find</code> command).</p>
  
  <p>E.g., if I have the following directory and files, </p>
  
  <pre><code>$ ls -l /tmp/dir1
  total 0
  -rw-r--r--  1 joeuser  joemama  0 Jul 15 10:19 1A
  -rw-r--r--  1 joeuser  joemama  0 Jul 15 10:19 1B
  </code></pre>
  
  <p>I want to send each of the filenames <code>1A</code> and <code>1B</code> to <code>basename</code>. Here's several ways I've tried:</p>
  
  <pre><code>#!/bin/bash
  
  cmd="find /tmp/dir1 -exec basename {} \;"
  echo; echo "One slash: $cmd"
  $cmd
  
  cmd="find /tmp/dir1 -exec basename {} \\;"
  echo; echo "Two slashes: $cmd"
  $cmd
  
  cmd="find /tmp/dir1 -exec basename {} \\\;"
  echo; echo "Three slashes: $cmd"
  $cmd
  
  # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  # The first of these gets the desired result, but I want the "\;" in $cmd.
  # The second shows that the "\;" is being treated as part of the -exec
  # option, not its terminator.
  
  cmd="find /tmp/dir1 -exec basename {}"
  echo; echo "No slash, will add extra '\;': $cmd"
  $cmd \;
  
  cmd="find /tmp/dir1 -exec echo {} \;"
  echo; echo "Command is echo, not basename. One slash, will add extra '\;': $cmd"
  $cmd \;
  </code></pre>
  
  <p>And the output:</p>
  
  <pre><code>$ /tmp/gofind1 
  
  One slash: find /tmp/dir1 -exec echo {} \;
  find: -exec: no terminating ";" or "+"
  
  Two slashes: find /tmp/dir1 -exec echo {} \;
  find: -exec: no terminating ";" or "+"
  
  Three slashes: find /tmp/dir1 -exec echo {} \\;
  find: -exec: no terminating ";" or "+"
  
  No slash, will add extra '\;': find /tmp/dir1 -exec echo {}
  dir1
  1A
  1B
  
  Command is echo, not basename. One slash, will add extra '\;': find /tmp/dir1 -exec echo {} \;
  /tmp/dir1 \;
  /tmp/dir1/1A \;
  /tmp/dir1/1B \;
  </code></pre>
  
  <p>Is there a way to properly escape the "\;" so it can be stored in <code>$cmd</code>? Or can I rest assured that adding the <code>\;</code> inside the <code>($( ... ))</code> won't break something else later?</p>