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

PathTypeValid
/Root directory
/home/userAbsolute path
/usr/local/binAbsolute path
/var/log/system.logAbsolute file path
./relative/pathRelative path
./file.txtRelative file
../parent/directoryParent directory
/path/to/directory/Trailing slash
/path-with-dashes/file_name.extDashes and underscores
/path/with.dots/file.tar.gzMultiple dots
relative/pathInvalid relative (no ./)
C:/Windows/System32Windows path
/path with spaces/fileContains spaces
(empty string)Empty string
//double/slashDouble slash
/path//fileDouble slash in middle