BudiBadu Logo
Samplebadu

Bash by Example: List Directory

Bash 5.0+

Listing files and directories using the ls command with various formatting options and glob patterns for filtering, understanding ls flags like -l for long format, -a for hidden files, and -h for human-readable sizes, using wildcards and glob patterns to filter listings, and parsing ls output safely in scripts.

Code

#!/bin/bash

mkdir -p demo
touch demo/a.txt demo/b.log demo/c.txt

echo "--- Basic List ---"
ls demo

echo -e "\n--- Long Format ---"
ls -l demo

echo -e "\n--- All Files (Hidden) ---"
touch demo/.hidden
ls -la demo

echo -e "\n--- Globbing (*.txt) ---"
# List only text files
ls demo/*.txt

echo -e "\n--- Iterate Files ---"
for file in demo/*; do
    echo "Processing $file"
done

rm -rf demo

Explanation

The ls command is the primary way to list directory contents.

  • ls: Simple list of names.
  • ls -l: Long format (permissions, owner, size, date).
  • ls -a: All files, including hidden ones starting with ..
  • ls -h: Human-readable sizes (e.g., 1K, 234M).

Globbing uses wildcards like * to match filenames. *.txt matches all files ending in .txt. This is handled by the shell itself before the command runs.

Code Breakdown

10
ls -l provides detailed info. Each line represents a file with its permissions, owner, group, size, and modification time.
18
Globbing *.txt expands to the list of matching files. If no files match, ls will report an error (or print the pattern literal depending on shell options).