Working with pwd, ls, and cd

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 15 of 205

The commands pwd, ls, and cd form the core of moving around a file system from the terminal. pwd tells you where you are, ls shows what is there, and cd takes you somewhere else. This lesson explains how directories are organized, how each command works, and how to combine them to navigate confidently.

Understanding the Concept

Files on Linux and macOS are arranged in a tree of directories, which many graphical tools call folders. The top of the tree is the root directory, written as /. Every other directory sits somewhere below it.

/
├── home
│   └── student
│       ├── projects
│       │   ├── notes.txt
│       │   └── site
│       │       ├── index.html
│       │       ├── css
│       │       └── js
│       └── my docs
└── usr

Bash always has a current working directory, which is the place where commands that use relative file names look first. Your shell begins in your home directory, such as /home/student on Linux or /Users/student on macOS. Every command that takes a path is interpreted relative to the current directory unless the path starts with /.

The examples in this lesson use the tree above, with the home directory shown as ~.

Printing the Working Directory with pwd

pwd stands for "print working directory". It prints the full path of the directory the shell is in:

pwd

Output:

/home/student

The result is an absolute path, which means it starts from / and spells out every directory on the way down. Use pwd whenever you are unsure where you are, especially before running a command that changes or deletes files.

Logical and Physical Paths

A directory can be reached through a symbolic link, which is a shortcut that points to another directory. The pwd built-in has two options for this:

  • pwd -L prints the logical path, including the names of links you followed. This is the default.
  • pwd -P prints the physical path, with every link resolved to the real directory.

Suppose ~/projects/link is a link to ~/projects/site:

cd ~/projects/link
pwd
pwd -P
pwd -L

Output (with the home directory shown as ~ for readability):

~/projects/link
~/projects/site
~/projects/link

The first and third commands report the path you typed. The second reports where the files really are.

Listing Directory Contents with ls

ls lists the names of the files and directories in a directory. Without arguments it uses the current directory:

cd ~/projects
ls

Output:

notes.txt  site

You can also pass a path to list a different directory, without moving there:

ls site

Output:

css  index.html  js

Hidden Files

Names that begin with a dot are hidden from the normal listing. They are mostly configuration files. Use -a to include them:

cd ~
ls
ls -a

Output:

my docs  projects
.  ..  .hidden  my docs  projects

The special names . and .. appear in every directory. A single dot means "this directory", and two dots mean "the parent directory". The option -A lists hidden files but leaves out . and ..:

ls -A

Output:

.hidden  my docs  projects

The Long Format

The -l option prints one line for each item, with details:

cd ~/projects
ls -l

Output:

total 4
-rw-r--r-- 1 student student    0 Nov 20 10:52 notes.txt
drwxr-xr-x 4 student student 4096 Nov 20 10:52 site

Reading a line from left to right:

FieldExampleMeaning
Type and permissionsdrwxr-xr-xThe first character is the type (- for a file, d for a directory), followed by nine permission characters
Link count4Number of hard links to the item
OwnerstudentThe user who owns it
GroupstudentThe group that owns it
Size4096Size in bytes
DateNov 20 10:52When it was last modified
NamesiteThe file or directory name

Permissions have their own lesson later. For now, notice that the leading d identifies site as a directory.

Add -h to print sizes in a human-readable form such as 4.0K or 1.2M:

ls -lh site

Output:

total 8.0K
drwxr-xr-x 2 student student 4.0K Nov 20 10:52 css
-rw-r--r-- 1 student student    0 Nov 20 10:52 index.html
drwxr-xr-x 2 student student 4.0K Nov 20 10:52 js

Other Useful Options

CommandWhat it does
ls -1One name per line
ls -FAdds a marker after each name: / for directories, * for executables
ls -d */Lists only the directories in the current directory
ls -ld siteShows details of the directory itself instead of its contents
ls -tSorts by modification time, newest first
ls -RLists directories recursively, including everything below them

Here are two of them in action:

ls -F
ls -R site

Output:

notes.txt  site/
site:
css  index.html  js

site/css:
style.css

site/js:
app.js

In the first output, the trailing slash marks site as a directory. In the recursive listing, each directory is shown as a heading followed by its contents.

Changing Directories with cd

cd means "change directory". It moves the shell to another directory, and the prompt and pwd update to match. It is a built-in, as explained in the previous lesson, because it must change the directory of the shell itself.

Absolute and Relative Paths

An absolute path starts with / and works from anywhere:

cd /usr
pwd

Output:

/usr

A relative path does not start with / and is resolved from the current directory:

cd ~/projects
cd site/css
pwd

Output:

~/projects/site/css

Starting from ~/projects, the path site/css leads down through site into css. Use .. to move up to the parent:

cd ..
pwd

Output:

~/projects/site

You can chain parent references. Each .. rises one level from where you stand now, so from ~/projects/site the path ../.. leads up two levels, to the home directory:

cd ../..
pwd

Output:

~

Shortcuts

Several shortcuts save typing:

CommandDestination
cdYour home directory
cd ~Your home directory
cd -The previous directory
cd ..The parent directory
cd /The root directory

The shortcut cd - returns to wherever you were before the last cd, and it prints the directory name as it goes. Bash tracks the previous directory in the variable OLDPWD:

cd ~/projects/site
cd ~
cd -

Output of the last command (the directory it returns to, printed in full):

/home/student/projects/site

Plain cd with no argument always takes you home, no matter how deep you are:

cd ~/projects/site/css
cd
pwd

Output:

/home/student

Directories with Spaces

If a directory name has a space, quote it or escape the space, so that Bash sees one argument:

cd "my docs"
pwd

Output:

/home/student/my docs

The form cd my\ docs works the same way. Tab completion, covered in the lesson on using the terminal, inserts the backslashes for you.

When cd Fails

If the directory does not exist, cd prints an error and returns a failing exit status, and the shell stays where it was:

cd nowhere
echo "status=$?"
pwd

Output in an interactive shell:

bash: cd: nowhere: No such file or directory
status=1
/home/student

Because cd returns a non-zero status when it fails, scripts often write cd somewhere || exit 1, so that they stop instead of running the rest of their commands in the wrong place.

Combining the Three Commands

A typical navigation routine uses all three:

pwd
ls
cd projects
pwd
ls -l
cd site
ls
cd ..
cd
pwd

Sample output, starting in the home directory:

/home/student
my docs  projects
/home/student/projects
total 4
-rw-r--r-- 1 student student    0 Nov 20 10:52 notes.txt
drwxr-xr-x 4 student student 4096 Nov 20 10:52 site
css  index.html  js
/home/student

Walking through the commands:

  1. pwd shows the starting point, the home directory.
  2. ls reveals two entries, my docs and projects.
  3. cd projects moves down one level, and pwd confirms the new location.
  4. ls -l shows details, including that site is a directory.
  5. cd site and ls move into it and show its three entries.
  6. cd .. goes back up to projects, and cd with no arguments returns home.
  7. The final pwd confirms that the shell is back in /home/student.

Working this way, you can orient yourself at any moment with pwd, discover what is nearby with ls, and move with cd.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Working with pwd, ls, and cd and get answers drawn from it.

Signed-in readers only.