Directory Operations
In this page:
Creating Directories Safely
mkdir -p creates any missing parent directories in one call and does not fail if the target already exists, making it the safe default for scripts.
Example: Creating Directories Safely
#!/bin/bash
mkdir -p project/src/utils
if [[ -d project/src/utils ]]; then
echo "nested directories created"
fi
rm -rf project
Login to try C/C++/Java/PHP code in the editor
Changing Directories Safely
cd can fail if the target does not exist or is not accessible. Chaining it with || exit 1 (or || return 1 inside a function) stops the script from continuing to operate in the wrong place.
Example: Changing Directories Safely
#!/bin/bash
mkdir -p work_area
cd work_area || exit 1
echo "Now in: $(pwd | xargs basename)"
cd ..
rmdir work_area
Login to try C/C++/Java/PHP code in the editor
Using pushd and popd
pushd dir changes directory while remembering where you came from on a stack, and popd returns to that remembered location. This is convenient for scripts that need to temporarily work elsewhere and come back.
Note: Redirect pushd/popd output to /dev/null in scripts since their default directory-stack printout is rarely useful there.
Example: Using pushd and popd
#!/bin/bash
mkdir -p temp_place
pushd temp_place > /dev/null
echo "working here: $(pwd | xargs basename)"
popd > /dev/null
echo "back to: $(pwd | xargs basename)"
rmdir temp_place
Login to try C/C++/Java/PHP code in the editor
Listing Directory Contents in a Script
While ls is fine for a human to glance at, scripts should generally prefer glob patterns or find to enumerate files, since ls output can be ambiguous with unusual filenames. Plain ls is still fine just to display a listing to a user.
Warning: Never parse ls output in scripts (e.g. for f in $(ls)); use globs (for f in *) or find instead.
Example: Listing Directory Contents in a Script
#!/bin/bash
mkdir -p listing_demo
touch listing_demo/a.txt listing_demo/b.txt
ls listing_demo
rm -rf listing_demo
Login to try C/C++/Java/PHP code in the editor
- Assuming
cdalways succeeds; scripts should check its exit status or usecd dir || exit 1to avoid silently continuing in the wrong directory. - Forgetting
mkdir -pis needed to create nested directories or to avoid an error when the directory already exists. - Not realizing
pushd/popdmaintain a stack, so nesting them incorrectly can leave you in an unexpected directory.
mkdir -pcreates parent directories as needed and does not error if the directory already exists.cd dir || exit 1is a safe pattern that stops the script if the directory change fails.pushd/popdpush and pop directories on a stack, letting you return to a previous location easily.lsinside scripts is best avoided for parsing; prefer globs orfindfor reliable filename handling.
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: