macOS安装GNU版本基础命令行工具coreutils

coreutils是在 macOS 上安装 GNU 版本的基础命令行工具。macOS 自带的是 BSD 版本的工具,而 GNU 工具功能更丰富,更接近 Linux 环境,对于开发、运维非常有帮助。


coreutils 包含哪些工具?

coreutils 提供了 Linux 上常用的命令行工具(约 100+ 个),例如:

GNU 命令 BSD/macOS 命令 说明
gdate date 支持 date -d 等 Linux 常用语法
gseq seq(macOS 没有) 生成数字序列
gcp, gmv, grm cp, mv, rm 更一致、功能更强
gsort sort 支持 --key--numeric-sort 等高级选项
gcut, guniq, ghead, gtail 各类文本处理增强命令
gsha256sum, gmd5sum macOS 无原生命令 哈希校验工具

安装后,这些 GNU 工具的命令前都会加个 g 前缀,避免与系统原生命令冲突

/usr/local/opt/coreutils/libexec/gnubin

mvpbang@mvpbang gnubin % ls 
'['	    chown    dir	 fmt	   ln	     nice      printenv   sha1sum     stat      touch	   uptime
 b2sum	    chroot   dircolors	 fold	   logname   nl        printf	  sha224sum   stdbuf    tr	   users
 base32     cksum    dirname	 groups    ls	     nohup     ptx	  sha256sum   stty      true	   vdir
 base64     comm     du		 head	   man	     nproc     pwd	  sha384sum   sum       truncate   wc
 basename   cp	     echo	 hostid    md5sum    numfmt    readlink   sha512sum   sync      tsort	   who
 basenc     csplit   env	 id	   mkdir     od        realpath   shred       tac       tty	   whoami
 cat	    cut      expand	 install   mkfifo    paste     rm	  shuf	      tail      uname	   yes
 chcon	    date     expr	 join	   mknod     pathchk   rmdir	  sleep       tee       unexpand
 chgrp	    dd	     factor	 kill	   mktemp    pinky     runcon	  sort	      test      uniq
 chmod	    df	     false	 link	   mv	     pr        seq	  split       timeout   unlink

安装方法

1
brew install coreutils

安装完成后,GNU 工具默认安装在:

/usr/local/opt/coreutils/libexec/gnubin

可选配置:自动使用 GNU 工具(覆盖 BSD 命令)

~/.zshrc~/.bash_profile 中添加:

1
export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"

这样你就可以直接用 date(实际用的是 GNU gdate),而不用写 gdate


适用场景

  • 写跨平台脚本(兼容 Linux)
  • 使用 date -dsort --keyseq 等 GNU 扩展
  • 重度使用 awk/sed/find/xargs 等文本处理
  • 搭配 gawk, gnu-sed, findutils 等,构建完整 GNU 环境