Unix Path Validation Regular Expression

Unix and Linux file system paths follow a hierarchical structure starting from the root directory (/). Paths can be absolute (starting with /) or relative (starting with ./ or ../). This regex validates common Unix path formats used in Linux, macOS, and other Unix-like operating systems, following the POSIX pathname specification. For Windows paths, see the Windows path validation article.

Recommended Solution

^(\/[^\/ ]*)+\/?$|^\.(\/[^\/ ]*)+\/?$|^\.\.\/([^\/ ]*\/)*[^\/ ]*$

Explanation

  • ^(\/[^\/ ]*)+\/?$ - Absolute paths:
    • \/ - Starts with a forward slash.
    • [^\/ ]* - Directory/file name (any characters except / and space).
    • + - One or more path segments.
    • \/? - Optional trailing slash.
  • ^\.(\/[^\/ ]*)+\/?$ - Relative paths starting with ./
  • ^\.\.\/([^\/ ]*\/)*[^\/ ]*$ - Relative paths starting with ../ (parent directory).

Notes

  • This regex validates the format of Unix paths but does NOT verify if the path exists on the filesystem.
  • This pattern does NOT allow spaces in path names. Modify [^\\/ ]* to [^\\/]* to allow spaces if needed.
  • Hidden files and directories (those starting with a dot) are supported (e.g., /home/user/.config).
  • Special characters like *, ?, and [] which have meaning in shell globbing are allowed in this pattern but may need escaping in actual use.
  • The pattern accepts both files and directories. Trailing slashes typically indicate directories but are not required.
  • Symbolic links are validated by format but not resolved or distinguished from regular files/directories.
  • For more robust path validation, consider using filesystem APIs in your programming language.

Implementation

const unixPathRegex = /^\/(?:[^\/ ]+\/)*[^\/ ]*$|^\.(?:\/[^\/ ]+)+\/?$|^\.\.\/(?:[^\/ ]+\/)*[^\/ ]*$/;
const isValidUnixPath = (path) => unixPathRegex.test(path);

Test Cases

PathValid
/
/home/user
/usr/local/bin
/var/log/system.log
./relative/path
./file.txt
../parent/directory
/path/to/directory/
/path-with-dashes/file_name.ext
/path/with.dots/file.tar.gz
relative/path
C:/Windows/System32
/path with spaces/file
(empty string)
//double/slash
/path//file