title: Bash quoted array expansion
body: <p>WHen I write a bash program I typically construct calls like follows:</p>
  
  <pre><code>declare -a mycmd=( command.ext "arg1 with space" arg2 thing etc )
  
  "${mycmd[@]}" || echo "Failed: foo"
  </code></pre>
  
  <p>Where <code>die foo</code> is a bash function that prints <code>Error foo</code> and exits.</p>
  
  <p>But if I want to be clear about the error reason, I want to print the failed command:</p>
  
  <pre><code>"${mycmd[@]}" || echo "Failed: foo: ${mycmd[*]}"
  </code></pre>
  
  <p>So the user can run the dead command and find out <em>why</em>.  However, quoting is lost on this pass - the Failed message arguments that have spaces or escaped characters are not printed in a way that can be cut-n-pasted and run.</p>
  
  <p>Does anyone have a suggestion for a compact way to fix this problem?</p>
  
  <hr>
  
  <p>I think the problem is the way bash deals with argument parsing for commands, and the way (builtin) echo handles arguments.  Another way of stating the problem is:</p>
  
  <p>How can I <em>print</em> the quotes around arguments with spaces in the following bash example (which must be run as a script, not in immediate mode):</p>
  
  <pre><code>#!/bin/bash
  mkdir qatest; cd qatest
  declare -a myargs=(1 2 "3 4")
  touch "${myargs[@]}"
  ls
  echo "${myargs[@]}"
  </code></pre>
  
  <p>actual result:</p>
  
  <pre><code>1  2  3 4
  1 2 3 4
  </code></pre>
  
  <p>desired result</p>
  
  <pre><code>1  2  3 4
  1 2 "3 4"
  </code></pre>
  
  <p>OR</p>
  
  <pre><code>1  2  3 4
  "1" "2" "3 4"
  </code></pre>
  
  <p>In few additional bash code characters.</p>
  
  <hr>
  
  <h2>Question closed: @camh answered it magnificently:</h2>
  
  <p>updated script:</p>
  
  <pre><code>#!/bin/bash
  mkdir qatest; cd qatest
  declare -a myargs=(1 2 "3 4")
  touch "${myargs[@]}"
  ls
  echo "${myargs[@]}"
  echo $(printf "'%s' " "${myargs[@]}")
  </code></pre>
  
  <p>output:</p>
  
  <pre><code>1  2  3 4
  1 2 3 4
  '1' '2' '3 4'
  </code></pre>