{:check ["true"], :rank ["cp" "mv" "rm" "summary"]}

Index

Working With Files

Cp

Copy cp command

  • Let's start with copying a single file.

    Let's start with the most general syntax:

    $ cp <source> <target>
    
    split=8
    $ cp ./assignment_1/report.pdf ./assignment_2/report.pdf
    

    Here we copy the report for assignment 1 as the report for assignment 2.

  • Copy a file to some directory.

    The <target> can be a directory, in which case, cp will make a copy of the source file in that directory with the same file name.

  • Copy multiple files to some directory.

    $ cp <source_1> <source_2> <source_3> <target>
    
  • Copy a directory to another directory.

    $ cp -r <source_directory> <target_directory>
    
  • The target directory ambiguity:

    box

    cp has different behaviour depending on whether the target directory exists.

    Consider the command:

    $ cp -r ../report/ ./my_files
    
    • CASE (1): if ./my_files does not exist.

      cp will create ./my_files, and then copy all files and directories (recursively) under ../reports/ to ./my_files.

    • CASE (2): if ./my_files already exists.

      cp will copy all files and directories to ./my_files/reports.

    • The -T option will always ensure that cp behaves cas in CASE (1).

Mv

Moving files using mv

  • Moving single file

    $ mv <source_file> <target_file>
    

    Examples:

    split=8
    \$ mv my_report.pdf ~/work/report.pdf
    
    \$ mv my_report.pdf report.pdf
    

    We can use this to move a file to a new location, or use it to rename a file.

  • Moving files to target directory

    $ mv <source_1> <source_2> ... <target_directory>
    
  • The target directory ambiguity

    box

    mv has the same target directory ambiguity behaviour that cp suffers from.

    It also supports the -T option to suppress the target directory ambiguity.

Rm

Removing files or directories

  • Removing one or more files

    $ rm <file_1> <file_2> ...
    
  • Removing an empty directory

    $ rmdir <directory>
    
  • Removing non-empty directory

    split=8
    $ rm -r <directory>
    

    This deletes all contents in the directory, and then the directory itself.