Why does 'cp -f' not work anymore?

cs at zip.com.au cs at zip.com.au
Thu Nov 3 22:56:54 UTC 2005


On 03Nov2005 07:19, Michael Velez <mikev777 at hotmail.com> wrote:
| From: redhat-list-bounces at redhat.com [mailto:redhat-list-bounces at redhat.com]
| > On Behalf Of Cameron Simpson
| > How about this:
| > 	# define smarter wrapper
| > 	cp()
| > 	{ [ "x$1" = x-f ] || set -- -i ${1+"$@"}
| > 	  command cp "$@"
| > 	}
| > 
| > This should turn on -i mode if you don't supply a -f.
| 
| Hope you don't mind.  I liked your function and decided to use it and
| changed it to be more in line with cp syntax.
| 
| cp()
| {
| 	[ $((`expr " $*" : '.* -[a-zA-Z]*f[a-zA-Z]* .*'`)) -ne 0 ] || 
| 	[ $((`expr " $*" : '.* --force .*'`)) -ne 0 ] || 
| 	set -- -i ${1+"$@"}
| 	command cp "$@"
| }
| 
| This function checks for --force and -f anywhere on the command line, as
| well as it allows options to be combined with -f, such as -rfv.

Well, this has two problems.

First is this:

	cp -- foo -f dir/.

to copy the files "foo" and "-f" into "dir".

Second, and one I care about more, is the use of expr.  I see this and
variants using grep et al all the time when doing pattern matches in
the shell. It is ugly and Very Slow.

It requires forking subprocesses (very slow, and it will bite you when you
embed it in other automation as it scales up badly) and it's hard to read.

Try this, addressing both problems:

    cp()
    {
      __cp_iopt=-i
      for __cp_arg
      do  case "$__cp_arg" in
	    --)	break ;;
	    -f* | -[a-z]*f* | --force )
		    __cp_iopt=; break ;;
	    -*)	;;
	    *)	break ;;
      done
      set -- $__cp_iopt ${1+"$@"}
      command cp "$@"
    }

This uses the shell's builtin glob matching via the case statement and
thus no subprocesses. It's easier to read because we've avoided expr. And
it correctly parses the argument sequence to handle the "--" terminator
(or, indeed, a plain old filename ending the options).

Cheers,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

Son, all the beautiful, intelligent, healthy young women are taken. It's a
basic law of the universe, and if you don't like it, go somewhere else.
                                  -- Ken Johnson's dad, 1906-1992




More information about the redhat-list mailing list