How can I make -f override -i with cp?

Discussion in 'Command Line' started by KenJackson, Feb 21, 2012.

  1. KenJackson

    KenJackson Active Member

    Messages:
    129
    Likes Received:
    27
    Trophy Points:
    28
    I have a number of aliases in my ~/.bashrc file, including this one:
    Code:
    alias cp="/bin/cp -i"
    The -i switch make cp prompt me if it's going to overwrite an existing file. That's normally what I want.

    But if I use the -f switch, I want it to take precedence and force the copy, regardless of whether it overwrites a file. But it doesn't work. Actually, it doesn't matter if I use the alias or not--when you use -i and -f in the same command, the -i overrides the -f.


    Code:
    $ touch test1 test2
    $ /bin/cp -i -f test1 test2
    /bin/cp: overwrite `test2'?
    I guess I could come up with some elaborate function to inspect all the arguments, but I'm hoping for a simpler solution. Is there one?
  2. Rob

    Rob Administrator Staff Member

    Messages:
    565
    Likes Received:
    171
    Trophy Points:
    43
  3. KenJackson

    KenJackson Active Member

    Messages:
    129
    Likes Received:
    27
    Trophy Points:
    28
    But that would violate the "that's normally what I want" clause.
  4. grim76

    grim76 Active Member Staff Writer

    Messages:
    177
    Likes Received:
    48
    Trophy Points:
    28
    I think if you refer to cp as /bin/cp in place of just cp it should allow the override.
  5. Rob

    Rob Administrator Staff Member

    Messages:
    565
    Likes Received:
    171
    Trophy Points:
    43
    Ok, then how about:

    Code:
    alias cpi="/bin/cp -i"
    
    The fact that you're using -i means it'll be interactive no matter what.. (as far as I know)
  6. KenJackson

    KenJackson Active Member

    Messages:
    129
    Likes Received:
    27
    Trophy Points:
    28
    I think this function instead of the alias would do what I want.
    But I haven't tested it and I'm not sure I'm going to bother with it.

    Code:
    function cp()
    {
        ARGS=() IF=-i
        while test $# -gt 0; do
            case "$1" in
                -i|-f) IF=$1                 ;;
                *)     ARGS[${ARGS[*]}]="$1" ;;
            esac
            shift
        done
        /bin/cp $IF "${ARGS[@]}"
    }

Share This Page