How do I look at the source code for a command?

Debian (and derivatives)

Run dpkg -S /path to see which package /path belongs to:

$ dpkg -S /bin/echo
coreutils: /bin/echo

Get the source (I'm on Ubuntu):

$ apt-get source coreutils
Reading package lists... Done
Need to get 5,755 kB of source archives.
Get:1 http://jp.archive.ubuntu.com/ubuntu xenial/main coreutils 8.25-2ubuntu2 (dsc) [2,071 B]
Get:2 http://jp.archive.ubuntu.com/ubuntu xenial/main coreutils 8.25-2ubuntu2 (tar) [5,725 kB]
Get:3 http://jp.archive.ubuntu.com/ubuntu xenial/main coreutils 8.25-2ubuntu2 (diff) [28.0 kB]
Fetched 5,755 kB in 3s (1,758 kB/s)
gpgv: Signature made 2016年02月18日 22時28分36秒 JST using RSA key ID 73F3F233
gpgv: Can't check signature: public key not found
dpkg-source: warning: failed to verify signature on ./coreutils_8.25-2ubuntu2.dsc
dpkg-source: info: extracting coreutils in coreutils-8.25
dpkg-source: info: unpacking coreutils_8.25.orig.tar.xz
dpkg-source: info: unpacking coreutils_8.25-2ubuntu2.debian.tar.xz
dpkg-source: info: applying no_ls_quoting.patch
dpkg-source: info: applying 61_whoips.patch
dpkg-source: info: applying 63_dd-appenderrors.patch
dpkg-source: info: applying 72_id_checkngroups.patch
dpkg-source: info: applying 80_fedora_sysinfo.patch
dpkg-source: info: applying 85_timer_settime.patch
dpkg-source: info: applying 99_kfbsd_fstat_patch.patch
dpkg-source: info: applying 99_hppa_longlong.patch
dpkg-source: info: applying 99_float_endian_detection.patch

Find the file:

$ cd coreutils-8.5 
$ find src -iname '*echo*'
src/echo.c

The rest is up to you.


RHEL/Fedora

Run rpm -qf /path

$ rpm -qf /usr/bin/echo
coreutils-8.25-17.fc25.x86_64

Download the source package (use yum for RHEL):

$ dnf download coreutils --enablerepo="*source"

Extract the sources, patches from the SRPM package downloaded in current directory, change to the directory where the files are extracted and find your file:

$ rpmbuild -rp coreutils-8.25-17.fc25.src.rpm
$ cd ~/rpmbuild/BUILD/coreutils-8.25/
$ find src -iname '*echo*'
src/echo.c

You can rebuild the package using rpmbuild --rebuild coreutils-8.25-17.fc25.src.rpm, which will produce the RPMs that you can directly install on your system.

If you need to do some modification to fedora packages, it is much easier to go the maintainer way: Install fedpkg, clone the repository, do the modifications (using patches) and rebuild the package with modifications:

$ sudo dnf install fedpkg
$ fedpkg clone coreutils
$ cd coreutils
$ # do the modifications
$ fedpkg local