Navigation basics
Linux commands: pwd
Learn how the Linux pwd command prints your current working directory, so you always know exactly where you are in the filesystem when you feel lost.
Whenever you feel lost in the filesystem, call pwd to know where you are:
pwd
The name stands for print working directory. The output is the absolute path of the folder you’re in right now:
/Users/flavio/projects/site
Every shell session has a current working directory. It’s the folder the shell considers “here”. When you type a relative path like notes.txt, the shell looks for it starting from that folder. Same command, different folder, different file. That’s why knowing where you are matters so much.
I run pwd all the time. After a few cd jumps, before a command that deletes something, or when a script behaves differently in two terminals and I suspect I’m not where I think I am.
Let’s see the difference between a relative and an absolute path. Create a file and refer to it both ways:
touch notes.txt
ls notes.txt
ls "$(pwd)/notes.txt"
Both ls calls print notes.txt, because they point to the same file. The second one builds an absolute path by pasting the output of pwd in front of the file name. I quoted $(pwd) because a folder name can contain spaces, and without quotes the shell would split the path in two.
The shell also keeps the current path in a variable called $PWD, so you can print it without running the command:
echo "$PWD"
There’s one option worth knowing: -P. It resolves symbolic links and prints the physical path. Plain pwd prints the logical path, the route you used to get there. Try it with a symlink:
mkdir fruits
ln -s fruits newfruits
cd newfruits
pwd
pwd -P
The first pwd says you’re in newfruits. The second one tells the truth:
/Users/flavio/newfruits
/Users/flavio/fruits
This matters when a script compares paths and they don’t match even though they point to the same place.
A common mistake is trusting the prompt instead of pwd. Many prompts only show the last folder name, so site could be ~/projects/site or ~/backup/site. If you run rm -rf dist in the wrong site, nothing warns you. A quick pwd before a destructive command costs one second and can save you a bad afternoon.
Try this: open two terminals, cd into different folders in each, and run pwd in both. The same relative command will act on different files depending on which terminal you type it in.
This command works on Linux, macOS, WSL, and anywhere you have a UNIX environment
Lesson completed