Skip to content
Advertisement

How do I correct this printing out copied files from directory in Unix Bourne Shell?

So i need to write a Unix Bourne Shell to to copy all the files from the directories named dir1 and dir2 into a new directory named dir3.

The script first copies all the files from dir1 into dir3.

The script then copies every file from dir2 to dir3 subject to these conditions: if the file from dir2 is not already present in dir3, or if the dir2 file is newer than the same dir3 file it will overwrite its namesake in dir3.

These should be the output:

JavaScript
JavaScript

So technically because dir2 a.c is created 1 minute later than dir1 a.c so it gets pasted in to dir3, overwriting the previously pasted dir1 a.c.

This does not apply to dir2 b.c because it was created earlier than dir1 b.c.

However, my output is something like this:

JavaScript

Here is my code:

JavaScript

These bits are wrong i suppose but cannot find out what is wrong…

JavaScript

Thanks so much in advance. Much appreciated

Advertisement

Answer

Don’t use a series of elifs, when a loop will do. Only return an exit code of 0 when all is well, not when something goes wrong:

JavaScript

And mkdir already will return an error if the destination directory exists, so there’s no need to write redundant code. This is enough:

JavaScript

Except for the output to the user, the file copy while loops aren’t really needed. Just use cp with the -u or --update, and -v or --verbose switch; see man cp for details. Both while loops can together be reduced to one line:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement