1
1
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?
1
1
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?
1
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
tmp=(~/temp/*.xyz)
cp -- "${a[0]}" ./
On other shells, you can do it this way (note that this overwrites the positional parameters):
set -- ~/temp/*.xyz
cp -- "$1" ./
0
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`" .