4

The command that I'm trying to execute for copying a file to a directory is given below :

cp /Users/anish/.m2/repository/org/apache/commons/commons-lang3/3.8.1/commons-lang3-3.8.1 /Volumes/Local Disk/Software Development/Courses/Maven/maven-learn-workspace/hello/target

After executing this, I'm getting this message :

usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file target_file
       cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file ... target_directory

Can anybody tell what needs to be added so that this command executes ?

20

You need to protect any whitespace in the names with either "" or \

cp foo 'path/with spaces/to/target'
cp foo path/with\ spaces/to/target

Additionally

  • Using Tab Completion in bash and other shells will automatically insert \ where necessary
  • Drag&drop of a file/directory from Finder into a Terminal window will insert the full path of said file/directory, with appropriate escapes
  • ditto is an alternative to cp which is better at handling metadata, resource forks and other specialities of macOS-specific filesystems.
  • If you want/need to use environment variables as part of a path (path/to/$TARGET/directory), use "" instead of '' but look out for $ as part of directory/file names
| improve this answer | |
  • 2
    I thought the command prompt automatically adds quotes around the path when you press the tab key for autocompletion. – Clockwork Jan 18 at 20:46
  • 7
    @Clockwork It does. But not everybody uses autocompletion, and it won‘t help in scripts. – nohillside Jan 18 at 20:53
  • 5
    You can also drag items from the Finder into a Terminal window, and it'll paste in the path with appropriate escapes. – Gordon Davisson Jan 18 at 20:56
  • 3
    Always protect with quotes. I prefer single apostrophe, as it will cause less interpolation, for instance if the filename contains an environment variable. That may be my habit of using system() from perl speaking. I often make a variable of the quoted filename, with an if to change ' to " if the filename contains '. I blow an exception if the filename contains both ' and ". – Harper - Reinstate Monica Jan 18 at 21:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .