0

I have a requirement where I need to copy some files from one location to other (Where the file may exist). While doing so,

  1. I need to take a backup if the file already exists.
  2. Copy the new file to the same location

I am facing problem in point 2. While I am trying to get the destination path for copying files, I am unable to extract the directory of the file. I tried using various options of find command, but was unable to crack it.
I need to trim the file name from the full file path so that it can be used in cp command. I am new to shell scripting. Any pointers are appreciated.

2 Answers 2

2

You can use

cp --backup

-b'--backup[=METHOD]' *Note Backup options::. Make a backup of each file that would otherwise be overwritten or removed. As a special case, `cp' makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. One useful application of this combination of options is this tiny Bourne shell script:

      #!/bin/sh
      # Usage: backup FILE...
      # Create a GNU-style backup of each listed FILE.
      for i; do
        cp --backup --force -- "$i" "$i"
      done
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but when I am using -b, I am getting error that "b" is not a recognized flag.
Install GNU cp from coreutils
0

If you need only the filename, why not do a

basename /root/wkdir/index.txt

and assign it to a variable which would return only the filename?

1 Comment

mani and dtmilano: Thanks for your responses. Found another way of doing it, I am now using dirname command to extract the file directory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.