Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble implementing cp -u in shell script

Tags:

linux

bash

For a school project, I have a shell script that is supposed to copy the files in two directories (without looking at subdirectories) into a third directory. I'm testing out the -u command so that if two files have the same name, only the newer one will get copied over (that's also a spec). My shell script looks like this (excluding #! and error checking):

cd $1 #first directory

for file in `ls`; do
    if [ -f $file ]; then
        cp "$file" ../$3 # $3 is the third directory
    fi
done

cd ../$2

for file in `ls`; do
    if [ -f $file ]; then
        cp -u "$file" ../$3
    fi
done

My current shell script will copy files that don't exist in directory 3 already, and it won't overwrite a newer file with an older file with the same name. However, my shell script doesn't overwrite an older file with a newer file of the same name in directory 3. I don't think there's anything wrong with the -u command. Can you help find the bug in my code? Thanks!

like image 996
user4793385 Avatar asked Jul 23 '26 11:07

user4793385


1 Answers

You are missing the -u option in the first loop:

cp "$file" ../$3 # $3 is the third directory

should instead read:

cp-u"$file" ../$3 # $3 is the third directory

like image 123
Mad Physicist Avatar answered Jul 25 '26 02:07

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!