linuxshellcopy

Copy and overwrite a file in shell script


I want to copy a certain file to a location, irrespective of that file already exists in the destination or not. I'm trying to copy through shell script.But the file is not getting copied. I'm using the following command

/bin/cp -rf /source/file /destination

but that doesn't work.


Solution

  • This question has been already discussed, however you can write a little script like this:

    #!/bin/bash
    if [ ! -d "$2" ]; then
      mkdir -p "$2"
    fi
    cp -R "$1" "$2"
    

    Explaining this script a little bit

    1. #!/bin/bash: tells your computer to use the bash interpreter.

    2. if [ ! -d "$2" ]; then: If the second variable you supplied does not already exist...

    3. mkdir -p "$2": make that directory, including any parent directories supplied in the path.

      Running mkdir -p one/two/three will make:

      $ mkdir -p one/two/three
      $ tree one
      one/
      └── two
          └── three
      

      If you don't supply the -p tag then you'll get an error if directories one and two don't exist:

      $ mkdir one/two/three
      mkdir: cannot create directory ‘one/two/three’: No such file or directory
      
    4. fi: Closes the if statement.

    5. cp -R "$1" "$2": copies files from the first variable you supplied to the directory of the second variable you supplied.

      So if you ran script.sh mars pluto, mars would be the first variable ($1) and pluto would be the second variable ($2).

      The -R flag means it does this recursively, so the cp command will go through all the files and folders from your first variable, and copy them to the directory of your second variable.