realpath Command

The realpath command in Linux is used to print the canonicalized absolute pathname of a file or directory. This means it resolves all symbolic links (symlinks), and processes all . (current directory) and .. (parent directory) components in the path, providing the true, absolute, and unambiguous path to the target.

Syntax

realpath [OPTION]... FILE...

Description

realpath is particularly useful in scripting and automation where you need to ensure that you are operating on the actual file or directory, regardless of how it was referenced (e.g., through multiple layers of symbolic links or complex relative paths). It provides a clean, absolute path that can be reliably used by other commands or applications.

Common uses include:

  • Resolving symbolic links to their ultimate target.
  • Converting relative paths to absolute paths.
  • Normalizing paths by removing redundant . and .. components.
  • Verifying the existence of a file or directory (it returns an error if the path doesn't exist).

Common Options

Option Description
-z, --zero End each output line with NUL, not newline.
--no-symlinks Do not expand symbolic links.
--strip, -s Strip all but the last component.

Examples

Get the canonical absolute path of a file

realpath my_symlink.txt
# If my_symlink.txt -> /home/user/documents/actual_file.txt # Output: /home/user/documents/actual_file.txt

Resolves a symbolic link to its actual file path.

Resolve a relative path to an absolute path

cd /usr/local/bin
realpath ../../etc/passwd
# Output: /etc/passwd

Converts a relative path containing .. components to its absolute form.

Normalize a path with redundant components

realpath ./my_dir/./another_dir/../file.txt
# Output: /current/working/dir/my_dir/file.txt

Cleans up a path by resolving . and .. entries.

Use in a script to get a definitive path

#!/bin/bash
CONFIG_FILE="./config/app.conf"
ABSOLUTE_CONFIG=$(realpath "$CONFIG_FILE")
echo "Absolute config path: $ABSOLUTE_CONFIG"

Ensures that ABSOLUTE_CONFIG always holds the true, absolute path.

See also