MacOS vs Linux — the cp command will trip you up!

BSD and Linux mascots

While building Firecode.io I was recently confronted with more than a hundred failing unit tests when running the test suite locally on my MacOS machine, rather than in a Linux Docker container the platform is configured to run tests in.

Screen showing test failures
Screen showing test failures

I use a MacBook Pro for software development, primarily because the BSD based MacOS provides a development experience that’s very similar to other Linux distros. All of my most frequently used navigation commands — cd, cp, mv, mkdir, touch, etc...work with 1:1 parity across both flavors of operating systems, or at least that’s what I thought. As I discovered after spending a good hour debugging these failures, there’s a subtle difference between the BSD and GNU implementations of the cp -R command, which I got hit with when running my tests on different environments.

Here’s the difference, illustrated with an example run in both MacOS and Linux:

So what would you expect to be printed with ls? Turns out the Linux GNU implementation of cp copies the source_directory directory to destination_directory, whereas on BSD MacOS the contents are unpacked and copied, as I’d expected it to behave on both environments:

GNU (Linux):

BSD (MacOS):

The trailing slash is significant in BSD, whereas the GNU implementation treats both source_directory/ and source_directory the same. The workaround, thankfully, is really simple — append a period when you intend for the contents to be copied and you’ll see the same behavior on both BSD and GNU : cp -R source_directory/. destination_directory/.

I hope this tidbit helps you write better cross environment code on MacOS and helps you save some time debugging unexpected results.

Ads Engineering @Twitter, part time entrepreneur — built Firecode.io, options and algorithmic trading enthusiast