0

Let's say I have file0, file1 file2.

When I copy file(0-2) into ./output/ dir with loop using backtick, I have strange outcome as following.

for idx in `ls file*`
 do
 cp file0 ./output/$idx
done
ls output

''$'\033''[00mfile1'$'\033''[0m' ''$'\033''[0m'$'\033''[00mfile0'$'\033''[0m' ''$'\033''[00mfile2'$'\033''[0m'

When I do echo $idx, it is ok. But only when I use $idx as filename, it happens.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    [Don't parse the output of ls](https://unix.stackexchange.com/questions/128985/why-not-parse-ls). Instead [do something like this](https://stackoverflow.com/questions/20796200/how-to-iterate-over-files-in-a-directory-with-bash?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) – JNevill Apr 13 '18 at 21:05
  • Possible duplicate of [How to iterate over files in a directory with Bash?](https://stackoverflow.com/questions/20796200/how-to-iterate-over-files-in-a-directory-with-bash) – jww Apr 13 '18 at 23:11

1 Answers1

0

No need to do command substitution at all:

for idx in file*
do
  cp file0 "./output/$idx"
done
ls output

but masking filenames, which might contain whitespaces etc. is always a good idea. These are of course not useful for copying but nonetheless valid filename characters, where only the '/' as delimiter between dirs and dir and file name and the binary zero '\0' as end-of-name-mark, are invalid (but you often need masking to use unusual characters in filenames).

Your output

''$'\033''[00mfile1'$'\033''[0m'
''$'\033''[0m'$'\033''[00mfile0'$'\033''[0m' 
''$'\033''[00mfile2'$'\033''[0m'

contains control sequences, which are often used to change the color of characters in the terminal.

Try

echo -e "\033[34mfile1 \033[33mfile0 \033[0m \033[43mfile2 \033[0m"

to see some different colors.

user unknown
  • 35,537
  • 11
  • 75
  • 121