The Curious Case of cd

I was preparing some training materials on command line basics and got a bit sidetracked on the subject of shell built-ins vs standalone programs.

Did you know that cd is a shell script? I didn't, but it makes perfect sense when you think about it. Here's what it looks like on macOS:

1
2
3
4
#!/bin/sh
# $FreeBSD: src/usr.bin/alias/generic.sh,v 1.2 2005/10/24 22:32:19 cperciva Exp $
# This file is in the public domain.
builtin `echo ${0##*/} | tr \[:upper:] \[:lower:]` ${1+"$@"}

And here's the original from FreeBSD:

1
2
3
4
#!/bin/sh
# $FreeBSD: releng/11.0/usr.bin/alias/generic.sh 151635 2005-10-24 22:32:19Z cperciva $
# This file is in the public domain.
builtin ${0##*/} ${1+"$@"}

Spot the difference? The way I see it, the character translations are there to account for the fact that HFS+, while not case sensitive by default, is case preserving. So when you do this:

$ mkdir /tmp/LaLaLa

LaLaLa is actually stored as LaLaLa, even though you can't do this:

$ mkdir /tmp/lalala
mkdir: /tmp/lalala: File exists

But you can still do this:

$ cd /tmp/lalala