0

I was trying to use cp to copy files from one directory to another by globing

for files in index/*
do
  file=$(echo $files|cut -d'/' -f2)
  cp -r "$files" ".target/file"
done

However, cp will give this warning if the directory is empty. I tried 2>/dev/null to mute this message but it did not work. I wonder how I could fix it.

User21749
  • 35
  • 2
  • 7
  • Set the `nullglob` option (`shopt -s nullglob`) such that the glob expands as the empty string instead of a literal `index/*`. Note that you don't use your `file`variable. – Renaud Pacalet Jul 06 '22 at 15:15
  • Not sure but maybe you want `".target/$file"` instead of `".target/file"`? – Jeff Holt Jul 06 '22 at 15:16
  • `file=${files#*/}` is a much faster way to strip the directory. – Charles Duffy Jul 06 '22 at 15:21
  • ...also more correct; `echo $files` is buggy. See [I just assigned a variable, but `echo $variable` shows something else](https://stackoverflow.com/questions/29378566/i-just-assigned-a-variable-but-echo-variable-shows-something-else). – Charles Duffy Jul 06 '22 at 15:22

1 Answers1

1

What about this: (not tested)

find /index -maxdepth 1 -type f -exec cp {} .target/ \;
  • -maxdepth 1 : only look in this directory
  • -type f : only take the files
  • -exec cp {} .target/ \; : execute a "file copy" action
Dominique
  • 16,450
  • 15
  • 56
  • 112
  • For GNU systems, you can do even better: `-exec cp -t ./target/ -- {} +` -- your current code starts a new copy of `cp` for each file; whereas `-exec ... {} +` fits as many files as possible onto each command line. – Charles Duffy Jul 06 '22 at 15:21
  • ...that said, if the OP really meant the `-r` (having directories as opposed to just files in `index/`), you might (1) want to do the same here; and (2) take off the `-type f`. – Charles Duffy Jul 06 '22 at 15:24