Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I tried using a command like

cp `ls ~/temp/*.xyz | head -1` ./

But that does not work. If I echo the value of command inside back ticks and put it manually in cp command it works. Any ideas?

share|improve this question
up vote 1 down vote accepted

The text produced by the backticks (or the alternate syntax $(…)), like text resulting from substituting a variable ($foo), is expanded by the shell: it is broken into words, and the words are interpreted as glob patterns (i.e. \[?* operate to match files). To avoid this issue, always use double quotes around variable and command substitutions.

There's a second issue: parsing the output of ls is a bad idea for various reasons.

If you use zsh as your shell, an easy way to do what you're attempting is

cp ~/temp/*.xyz([1]) ./

On other shells, this is harder. On the command line, you might risk using ls, if you know your file doesn't contain any nonprintable character (for ls's definition of nonprintable). In a script, this is calling for disaster; a simple two-liner in ksh or bash is

cp -- "${a[0]}" ./

On other shells, you can do it this way (note that this overwrites the positional parameters):

set -- ~/temp/*.xyz
cp -- "$1" ./
share|improve this answer

Maybe the matched file contains special characters (e.g. spaces) so you need to quote the back ticks expression:

cp "`ls ~/temp/*.xyz | head -1`" .
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.