18

I'm coming from Linux to macOS, and many of my scripts assume GNU versions of the utils provided in GNU coreutils.

I could just put the GNU coreutils bin directory in earlier in $PATH than /bin.

Is this commonly done? If I do it, what downsides/breakages should I expect in future?

2
  • 2
    Use full paths for the GNU utilities in your scripts. Dec 4, 2021 at 10:28
  • 2
    You could include a flag in your scripts, say "${USE_COREUTILS}". In your scripts, set it to 0 or set (defaults to 1 or unset), and in your rc file, include the line [ $USE_COREUTILS -eq 0 ] && PATH=$PATH:/path/to/coreutils/directory. This is how it would look in .bashrc anyway. I doubt mac shells are much different. As far as I know, it would work with .zshrc as well. I haven't tested the code, so you may need to iron out the kinks. Edit: or just use the Homebrew version mentioned below... : )
    – Nate T
    Dec 5, 2021 at 4:14

3 Answers 3

19

It will break any script which expects BSD-style utilities (different arguments, partially different functionality)

But you can install coreutils with Homebrew or Macports which will give them a g prefix (gcp etc). And then adapt your scripts to use those (depending on the platform they run).

17

While using un-prefixed coreutils has the potential to break any script expecting BSD-style programs, I have been using un-prefixed coreutils for almost 8 years now, and I've never run into a single issue. Given the anecdotal nature of that experience report you should take it with a grain of salt, but my experience has been that the reported dangers of un-prefixing are overblown.

1
  • 1
    Likewise. I flit between Linux at home and Mac at work (software dev) and haven't ever encountered a problem, while I've encountered plenty of problems with scripts that expect GNU utils not working on MacOS (usually switches that are GNU-only). And it's really nice to have my own stuff work the same across both OSes. Dec 6, 2021 at 17:41
3

I think it's safer to not have the GNU coreutils first in PATH, but I don't really know macOS.

A relatively easy way to get your existing scripts to use GNU coreutils is to redefine PATH in the beginning of each script.

export PATH=/path/to/coreutils:$PATH

This way you won't have to rename (or add full path) to all of the commands in a script.

1
  • +1 – this has the additional advantage of making this explicit in the script, rather than letting the script be dependent on (ie, hostage to) the environment the script is run in. Dec 6, 2021 at 14:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .